Wednesday, December 21, 2011

Dynamically load header message in column

In backing bean I have List vrsteAktivnosti and based on kratica property in my object I want to build header so it can easily be internationalized. Plus add sufix '_kratica' to property.
If for example kratica resolves to KR in my resource bundle I have key KR_kratica.

<ui:param name="kratica_3" value="#{aktivnostBean.vrsteAktivnosti.get(3).kratica}_kratica" />
<p:column headerText="#{msg[kratica_3]}">
...

Some expression language basics:
  • msg.someKey will look at message bundle for someKey
  • msg['someKey'] will look at message bundle for someKey
  • msg[someKey] will look at params to resolve property someKey
  • msg[aktivnostBean.vrsteAktivnosti.get(3).kratica] will look at objects property kratica and then look at msg bundle
  • msg[aktivnostBean.vrsteAktivnosti.get(3).kratica_kratica] will look at objects property kratica_kratica which does not exist, so use ui:param

Tuesday, December 13, 2011

Eclipse preferences

  1. Hot deploy on Tomcat - when you make changes to class it should be asap visible in Tomcat (JRebel would like that :)
    • Create Launch Configuration under Tomcat - Launch (Preferences), Debug is checked
    • This is working only on web project, not projects included in it
  2. General - check Show heap status
  3. General - Workspace - set Text file encoding
  4. General - Editors- Text Editors - Show line nubers
  5. Run/Debug - Console - uncheck Limit console output
  6. modify start shortcut: 
    • "C:\MyEclipse\myeclipseforspring.exe" -data D:\Workspace\Play -vmargs -Xmx768m -XX:MaxPermSize=384m -XX:ReservedCodeCacheSize=64m
  7. add latest Subclipse
  8. add bin and target folders to global svn ignore list
    • Windows - Preferences - Team - Ignored Resources - Add Pattern
    • enter bin then target then m2-target
  9. remove antivirus scan from workspace and eclipse installation directory
  10. add -showlocation as first line in eclipse.ini to show workspace location in title bar
Find resource in specific folder?
Open resource (Ctrl + Shift + R) - find start.jsp in msgbox subfolder:
*/msgbox/start.jsp

How to tell eclipse where is my java located?
Edit eclipse.ini file add line before -vmargs:
-vm (new line needed :)
C:\Java\jdk1.6.0\jre\bin\javaw.exe

How to change @author default field in Javadoc?
Edit eclipse.ini file, add line
-Duser.name=My name

Missing deployment assembly even if Dynamic Web Module is added as project facet
Add
 <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
to your .project file.

Quick Search
CTRL+SHIFT+L
https://marketplace.eclipse.org/content/quick-search-eclipse
https://spring.io/blog/2013/07/11/eclipse-quick-search/

Add decompiler
http://jadclipse.sourceforge.net/wiki/index.php/Main_Page
http://www.mkyong.com/java/java-decompiler-plugin-for-eclipse/

Ref:
http://wiki.eclipse.org/Eclipse.ini
What are the best JVM settings for Eclipse?
https://dzone.com/articles/show-workspace-location-title


TOMCAT - JVM parameters:
-Xms256m -Xmx1024m 
-XX:PermSize=64m -XX:MaxPermSize=512m
-Dorg.apache.el.parser.COERCE_TO_ZERO=false
-Dsun.jnu.encoding=UTF-8 
-Dfile.encoding=UTF-8


JVM params explained

-Xms<size>              set initial Java heap size
-Xmx<size>              set maximum Java heap size
-XX:PermSize<size>  set initial PermGen Size
-XX:MaxPermSize<size>  set the maximum PermGen Size
https://www.mkyong.com/java/find-out-your-java-heap-memory-size/

Thursday, November 17, 2011

Stubs vs Mocks


A stub is a piece of code that’s inserted at runtime in place of the real code, in order to isolate the caller from the real implementation. The intent is to replace a complex behavior with a simpler one that allows independent testing of some part of the real code.

Mocks replace real objects from the inside, without the calling classes being aware of it; They are objects pre-programmed with expectations which form a specification of the calls they are expected to receive.
The most important point to consider when writing a mock is that it shouldn’t have any business logic. It must be a dumb object that does only what the test tells it to do. It’s driven purely by the tests. This characteristic is exactly the opposite of stubs, which contain all the logic.

http://martinfowler.com/articles/mocksArentStubs.html

Monday, November 14, 2011

Aspect Oriented Programming (AOP)

Enables modularization of cross-cutting concerns (to avoid tangling and to eliminate scattering)

Concepts:

1. Advice - The actual work AOP will perform on a given object (around, before, after)
2. Join Point - places within your code that are eligible for advice; method execution
3. Pointcut - description of the joinpoint you want to advise; you list the criteria of the joinpoint you are interested in advising here. Eg. execution(public * *(..))
4. Aspect - functionality you actually want to add to an object (e.g. logging, security)

Aspects use Pointcuts to find Joinpoints to give Advice to ...



How AOP works?

AOP works by separating common concerns across the layers in separate classes and names them Aspect.
Aspects have APIs which aim to solve a common problem, like logging, and exception handling.
These are then invoked while intercepting the actual method invocation. Such APIs are termed Advice.
Advices are interceptors, which intercept original method invocation and wrap it around with handling of cross cutting concerns.
Now, for applying Advices to methods, AOP provides artifacts named JoinPoint.
Using a JoinPoint we could defne, which API invocation would be wrapped around by what Advice.

Weaving is a mechanism by which the aspects are applied to the designated classes and methods.
Weaving is generally done by generating byte code for the interceptors, using various libraries for byte code generation libraries, such as JavaAssist, BCEL, and ASM.
There are three places, any of which could be used to generate the bytecode. These are while compiling the code (Compile Time Weaving), loading the application known as (Load Time Weaving) and (Runtime Time Weaving) while actual method invocation is running.


Ref:
Spring doc
Learning Google Guice

Tuesday, November 8, 2011

Clearing JSF Form

On page you have form with input fields and button that can clear that fields.
Button is set to immediate since there is no need to do PROCESS_VALIDATIONS and UPDATE_MODEL_VALUES phases,
instead method is invoked in APPLY_REQUEST_VALUES phase.
First method can be used in JSF 1.x or 2.x, but second is based on AJAX event and is usable only in JSF 2.x
Better approach is with AJAX since there is no need to refresh whole page.

<h:commandButton value="Clear" id="clearButton">
<f:ajax event="click" render="@form" listener="#{myController.clearForm}" immediate="true" />
</h:commandButton>

public void clearForm(ActionEvent ae)
{
System.out.println("clearForm - via ActionEvent");
// clear bean values ...

// clear component values
UIComponent form = getContainingForm(ae.getComponent());
clearEditableValueHolders(form);
}

public void clearForm(AjaxBehaviorEvent ae)
{
System.out.println("clearForm - via AjaxBehaviorEvent");
// clear bean values ...

// clear component values
UIComponent form = getContainingForm(ae.getComponent());
clearEditableValueHolders(form);
}

private UIComponent getContainingForm(UIComponent component)
{
if (!(component.getParent() instanceof UIForm))
{
return getContainingForm(component.getParent());
}
else
{
System.out.println("getContainingForm: UIForm found");
return component.getParent();
}
}

private void clearEditableValueHolders(UIComponent form)
{
Iterator<UIComponent> iterator = form.getFacetsAndChildren();
while (iterator.hasNext())
{
UIComponent c = iterator.next();
if (c instanceof EditableValueHolder)
{
// Convenience method to reset this component's value to the un-initialized state.
((EditableValueHolder) c).resetValue();
}
clearEditableValueHolders(c);
}
}

Wednesday, October 26, 2011

Hibernate LazyInitializationException handling

In toString() method you want to output objects that are lazy fetched.
Solution that I use is via reflection with exception catching.
This will work only for fields declared in this class not super!

@Override:
public String toString()
{
   StringBuilder sb = new StringBuilder();
   sb.append(......);
   sb.append(ExceptionHandler.ignoreLazy(this, "zone"));
   return sb.toString();
}

public class ExceptionHandler:
public static String ignoreLazy(Object whom, String property)
{
  try
  {
    Field field = whom.getClass().getDeclaredField(property);
    field.setAccessible(true);
    Object print = field.get(tkoMeSadrzi);
    return print.toString();
 }
 catch (NoSuchFieldException e)
 {
   log.warn("DEVELOPER EXC ", e);
   return "NoSuchFieldException: " + e.getMessage();
  }
  catch (Exception lazy)
  { //ignore
    //log.debug("******* IGNORE LAZY : "+property);
    return "lazy loaded!";
  }
}

Hibernate show sql with parameters


#log hibernate prepared statements/SQL queries 
#(equivalent to setting 'hibernate.show_sql' to 'true')
log4j.logger.org.hibernate.SQL=debug

# log JDBC bind parameter runtime arguments
log4j.logger.org.hibernate.type=trace

To format sql output put this line in hibernate configuration file:
hibernate.format_sql

Wednesday, September 21, 2011

Calling procedure using SQL

In my case procedure does not need to return anything.
Calling it from DAO layer:

String queryString = "call myProcedure()";
Query query = getSession().createSQLQuery(queryString);
query.executeUpdate();

Thursday, September 15, 2011

Associations via criteria

Fetch data from one table by criteria on linked table

Person has Address. (1:1)
Address has field street.
I want to fetch all Persons that has Address with with specific street.
DetachedCriteria criteria= DetachedCriteria.forClass(Person.class);
criteria.createCriteria("address").add(Restrictions.eq("street", "WANTED"));

SELECT *
    FROM
        PERSON p
    inner join
        ADDRESS a
            on p.addressID=a.ID 
  WHERE
a.street=?

Fetch data from one table by having foreign key of linked table

Object A has 1:1 relation to object B.
Table A has foreign key to table B.
Class A has B.
I want to fetch class A and I only have ID of class B.
How to construct criteria?
SELECT * FROM a WHERE b_ID=?
//createCriteria on class A
criteria.add(Restrictions.eq("b.id", b.getId()));
criteria.list();


Fetch data from 3 linked tables

DPT has 1:n relation to OFFCOURTPAYMENT,
OFFCOURTPAYMENT has 1:n relation to SUBJECTASSEMBLY
How to fetch DPTs that belong to specific SUBJECTASSEMBLY?
select d.* from DPT d
INNER JOIN OFFCOURTPAYMENT o ON D.ACTIVEOCPOID = O.OID
INNER JOIN SUBJECTASSEMBLY sa ON SA.OID = O.SUBJECTASSEMBLYOID
where d.COMPANYOID= coid (4)
and D.CURRENTSTATE = 'MIROVANJE'
and SA.RECORDNUMBER = '1'
and SA.SUBJECTABLETYPE = 'OCS_DPT'


SubjectAssembly sa is passed in method
DetachedCriteria crit = DetachedCriteria.forClass(DailyParkingTicket.class);
crit.add(Restrictions.eq("currentDPTState", DPTState.StateName.MIROVANJE));
DetachedCriteria saCrit = crit.createCriteria("activeOcp").createCriteria("subjectAssembly"); // 2 inner joins will be generated
saCrit.add(Restrictions.eq("recordNumber", sa.getRecordNumber()));
saCrit.add(Restrictions.eq("subjectableType", sa.getSubjectableType()));
criteria.getExecutableCriteria(getSession()).list();


Notes

I want to fetch (via join) objects associated with my source object A:
A has list of Bs and B has C.
DetachedCriteria criteria= DetachedCriteria.forClass(A.class);
criteria.setFetchMode("B", FetchMode.JOIN); //must be present!
criteria.setFetchMode("B.C", FetchMode.JOIN);



// without DISTINCT_ROOT_ENTITY @ManyToMany returns full cartesian join!
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

Wednesday, September 14, 2011

@Column annotation and constraints in db


@Column(unique = true, nullable = false)
private Date startDate;

This annotation is description on startDate column when reading java file.
It is not used to stop inserting or updating database with false values, if you do not have constraints on table!
It can be used for generating table from entity class.

1 exception to the above rule:
If you try insert null into not null field declared in annotation it will throw Exception!

Friday, August 26, 2011

Open file with default program

In my example I have pdf file that I want to be opened as soon as it is saved to disk.


public static void openFile(File fileObj)
{
    StringBuilder sb = new StringBuilder();
    sb.append("cmd.exe /C start ");
    sb.append(fileObj.getAbsolutePath());
    System.out.println("openFile: " + sb);
    try
    {
        Runtime.getRuntime().exec(sb.toString());
    }
    catch (IOException e)
    {
        System.out.println("EEExxxccc");
    }
    }

Tuesday, August 23, 2011

Hibernate -distinct (with disjunction) via criteria

How to write distinct using Hibernate criteria API?

DetachedCriteria crit = DetachedCriteria.forClass(clazz);

Disjunction dis = Restrictions.disjunction(); // OR
dis.add(Restrictions.eq("billType", BillType.RACUN));
dis.add(Restrictions.eq("billType", BillType.STORNO));
crit.add(dis);

crit.setProjection(Projections.distinct(Projections.property("billSubtype")));

Criteria criteria = crit.getExecutableCriteria(getSession());
return crit.list();

select distinct B.BILLSUBTYPE from bill b where (B.BILLTYPE = 'RACUN' or B.BILLTYPE = 'STORNO')



http://www.jairrillo.com/blog/2009/01/29/how-to-use-left-join-in-hibernate-criteria/

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