Friday, July 22, 2011

Web -parameter transmission

(from jsf page to bean)

.xhtml:
<h:commandLink value="clickToTransfer" actionListener="#{activeBackingBean.methodName}" title="Hover effect">
<f:param name="myParam" value="TakeMe" />
</h:commandLink>

.java:
String parametar = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("myParam");

Ref:
4-ways-to-pass-parameter-from-jsf-page-to-backing-bean

Friday, July 15, 2011

Spring autowired behaviour

2 classes implement the same interface, 2 beans defined in configuration file for 2 different implementations.
eg. I have 2 beans of the same interface BillManager.

@Autowired
BillManager manager;

org.springframework.beans.factory.NoSuchBeanDefinitionException: No unique bean of type...

solution:
import org.springframework.beans.factory.annotation.Qualifier;

@Autowired
@Qualifier(value = "billManagerImpl_1") //write bean ID or name
BillManager manager;

Thursday, July 14, 2011

Hibernate - SQL Query

This post is written while using Hibernate 3.x version

String sqlQuery =
"select max(to_number(POLJE)) from TABLICA where COMPANYID=:company ";
SQLQuery query = getSession().createSQLQuery(sqlQuery);
query.setParameter("company", 1008);
query.addScalar("max(to_number(POLJE))", Hibernate.LONG);
//in db it is varchar

// you need to use StandardBasicTypes.LONG) in Hibernate v 4.3.x
Long l = (Long) query.uniqueResult();
if (l == null)
return 0L;
else return lL;
//if result is empty result set.. returned value will be null

Generated SQL:

select
    max(to_number(POLJE))
from
    TABLICA
WHERE
    COMPANYID=?


When using helper entity (that is not persisted) when data is fetched from many tables you can use ResultTransformer:
select B.BILLNUMBERPREFIX || B.BILLNUMBER AS billNumber, T.CREDIT, T.EVENTDATE ....
query.addScalar("billNumber").addScalar("credit", LongType.INSTANCE).addScalar("eventDate");
//necessary because property CREDIT is not the same as credit in Java (case sensitivity!) query.setResultTransformer(Transformers.aliasToBean(MyHelperClass.class));
log.info("\n\nSQL: " + query.getQueryString() + "\n\n");


How to map enum field?
import org.hibernate.impl.TypeLocatorImpl;
import org.hibernate.type.Type;
import org.hibernate.type.TypeResolver;
import org.hibernate.type.EnumType;

import org.hibernate.type.LongType;

Properties pmParams = new Properties();
pmParams.put("enumClass", "hr.samara.model.PaymentMethod");
pmParams.put("type", "12"); /* EnumType.STRING type = 12 */
Type pmType = new TypeLocatorImpl(new TypeResolver()).custom(EnumType.class, pmParams);

I removed default setter and made custom - bad :(
public void setSmsState(String smsState)
{
   this.smsState = SmsState.valueOf(smsState);
}


Ref:
http://www.journaldev.com/3422/hibernate-native-sql-example-addscalar-addentity-addjoin-parameter-example
https://stackoverflow.com/questions/9633337/hibernate-sql-transformation-fails-for-enum-field-type

Wednesday, June 1, 2011

Export to pdf

There is datatable and when user click on particular row it needs to be printed.

data table in xhtml:
 <ice:dataTable value="#{activeBackingBean.selectedEntity.subjectableList}" var="bill" ...

inside column put link component instead outputTex, which will pass bill number:
<ice:commandLink value="#{bill.GUINumber}" actionListener="#{activeBackingBean.billToPdf}" style="color:black;" title="Print bill">
   <f:param name="billNumber" value="#{bill.GUINumber}" />
</ice:commandLink>

In backing beanu there is (actionListener) method:
public void billToPdf(ActionEvent ae)
{
read request parametar and save object in class field for later use, call hidden button
String parameter = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("billNumber");
log.debug("billToPdf: " + parameter);
//find appropriate object (bill)
JavascriptContext.addJavascriptCall(FacesContext.getCurrentInstance(), "document.getElementById('PrintForm:PrintButton').click();");
}

hidden button in xhtml:
<ice:form id="PrintForm">
<ice:commandButton id="PrintButton" visible="false" actionListener="#"
onclick="{location.href='#{downloadServlet}?fileCreator=null&amp;fileType=pdf&amp;fileAction=activeBackingBean.billToPdf'}" />
</ice:form>

Click will call servlet which will call appropriate method in bean via reflection (fileAction -our method which needs to be called):
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
ctx.getBean("activeBackingBean");
Object result = MethodUtils.invokeMethod(bean, methodName, iS); //iS is InputStream
ServletOutputStream stream = response.getOutputStream();  ...

in backing beanu method that exports to PDF:
public FileObject billToPdf() throws JRException, IOException
{
if (log.isDebugEnabled()) log.debug("monthBillToPdf: " + bill);
return billManager.billToPdf(bill);
}


Second approach:
call servlet with submitted oid. Via refection call bean method, fetch appropriate object and print it.

Friday, May 20, 2011

Web app security

Principal
  • User, device or system that performs an action
Authentication
  • Establishing that a principal's credential's are valid
  • You are who you say you are? If so, you should know your password!
Authorization
  • Deciding if a principal is allowed to perform an action? 
  • Are you allowed to see this page? ( "to authorize" is to define access policy)
Secured item
  • Resource that is being secured
Confidentiality (data privacy)
  • Ensuring that an eavesdropper can’t read an HTTP message being sent from the client to the container
Data integrity
  • Ensuring that a hacker can’t alter the contents of an HTTP message while it is in transit from the container to a client.

Thursday, May 19, 2011

Spring web configuration

Configuration in web.xml

<!-- Loading Spring Application Context in web application-->
<context-param>
    <description>spring context</description>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/myApp-spring-web.xml</param-value>
or
    <param-value>classpath:/applicationContext-web.xml</param-value>
</context-param>

<listener>
    <description>fetch spring configuration file</description>
    <listener-class>
           org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>


Integration with JSF

Configuration in faces-config.xml

<application>
<!-- Enables injecting Spring beans as Faces managed properties -->
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>

Spring with Hibernate configuration

Loads object from the data source
<bean id="someRepository">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>

Instructs the container to look for beans with @Transactional and decorate them
<tx:annotation-driven transaction-manager="transactionManager"/>


A Hibernate SessionFactory for mapping entities from object to relation tables
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
   <property name="dataSource" ref="dataSource"/>
   <property name="annotatedClasses">
      <list>
         <value>package.Entity1</value>
         <value>package.Entity2</value>
      </list>
   </property>
   <property name="hibernateProperties">
      <value>
         hibernate.format_sql=true
         hibernate.show_sql=true
      </value>
   </property>
</bean>


A transaction manager for working with Hibernate SessionFactories
<bean id="transactionManager"  
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

Transparent Exception Handling
Annotate classes with @Repository

Wednesday, May 18, 2011

Transactions

Motivated by two independent requirements:
  • Cuncurrent database access
  • Resilience to system failures
A transaction is a sequence of one or more SQL operations treated as a unit.

ACID (atomicity, consistency, isolation, durability) is a set of properties that guarantee database transactions are processed reliably. In the context of databases, a single logical operation on the data is called a transaction. For example, a transfer of funds from one bank account to another, even though that might involve multiple changes (such as debiting one account and crediting another), is a single transaction.


Atomic
   Each unit of work is an all or nothing operation. (logging)
Consistent
   Database integrity constraints are never violated.
   It ensures the truthfulness of the database.
Isolated
   Isolating transactions from each other.
   Serializability - Operations may be interleaved, but execution must be equivalent to some sequential (serial) order of all transactions.
Durable
   Committed changes are permanent.
   (If system crashes after transaction commits, all effects of transaction remain in database.)


IMPLEMENTING
in class:
   @Transactional
(uses "transactionManager" by default)

By default, a transaction is rolled back if a RuntimeException has been thrown!
Default settings can be overridden with rollbackFor/noRollbackFor attributes.
After checked exception occurs transaction is commited.

in config file (xml):

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>
(Instructs the container to look for beans with @Transactional and decorate them)


Using transactions when only reading data allows Spring to optimize the transaction resources
e.g. 2 sql will be executed in 1 connection, prevents Hibernate from flushing its session, Oracle accepts only SELECT statements