Remote debugging in Fitnesse

  1. Start the Fitnesse
  2. When you want to debug a test, start by adding ?responder=test&remote_debug=true to the url for the test.
  3. Start the remote debugging process in your debugging tool. Remember to make sure you are using the right port. (Port 8000 if you are using the default settings for java).

How to create remote debugging application in Eclipse

  1. Run -> debug configurations…
  2. Create new Remote Java application and provide the Name as appropriate
  3. In Connect tab, choose the Project to debug.
  4. if you want more than one project to debug, Click Source tab and add relevant sources to debug.
  5. Provide the Host and port appropriately.

JPA 2.0 : Adding entity classes to PersistenceUnit *from different jar* automatically

There are several way to solve it:

  1. As described in Do I need <class> elements in persistence.xml?, you can set hibernate.archive.autodetection property and Hibernate should be able to look up all annotated classes from classpath. However, that’s not JPA spec compliant.
  2. If you are using Spring, from Spring 3.1.2 (or probably even a bit earlier), in LocalContainerEntityManagerFactoryBean, you can define packageToScan which will ask LocalContainerEntityManagerFactoryBean to scan in classpath to find all annotated classes. Again, not JPA spec compliant.

Configuring a Service Integration Bus in WebSphere 6.1

This Service Integration bus is needed to be able to define Destinations in WebSphere. These are in their turn bound to a QCF.

  • In the left-hand pane, expand Service Integration > Buses > New.
  • Enter a unique name in the Name field (for example server1_bus)
  • Next > Finished
  • Save the configuration.
  • To associate the current server with the newly created integration bus Select the just created bus
  • click Bus members under Topology.
  • Click Add and select the server you want to associate the integration bus.
  • Click Next (3x) > Finish

Create a physical queue for the request message

  • In the left-hand pane, expand Service Integration > Buses. Select the bus created earlier.
  • Under Destination resources click Destinations.
  • Click on New and choose Queue as the destination type. Enter an identifier such as inQueue. Accept the default Bus member.
  • Click Next (2x) > Finish > Save your changes.

Create a physical queue for the reply message

  • Repeat the steps taken in the Create a physical queue for the request message part but enter another identifier (e.g. outQueue)

Assign JMS settings against the newly created queues

  • Resources > JMS > JMS providers
  • pull-down menu > node…, server…
  • then Default messaging provider > Queues > New
  • Enter a name (for example inQueue) and JNDI name (for example jms/inQueue).
  • In the connection pane, select the Bus (server1_bus) and Queue (inQueue) you created earlier.
  • Click OK and Save the changes.
  • repeat this process but now for: name = outQueue JNDI-name = jms/outQueue

Create a queue connection factory for the queues

  • Resources > JMS > JMS providers > Default messaging provider > Queue connection factories > New
  • enter a name (for example queueConnectionFactory) and a JNDI name (for example jms/queueConnectionFactory).
  • Select the bus created earlier (server1_bus) as the bus name.
  • Click OK and Save the changes.

And finally

Once you have added the required connection factories and queues, you must stop and restart WebSphere Application Server v6.1 to activate the stuff.

Testing your Queues

The websphere distribution comming with RSA has a Universal Test Client. If WebSphere is started you can open this one by right-clicking on the server and choosing run universal testclient

  • in the UTC you do: Utilities > Send JMS message
    Send JMS Message

Queue JNDI Name: jms/inQueue
Queue CF JNDI Name: jms/queueConnectionFactory
Message: Hello World!

  • Send Message

This should work without errors

Check data on the queue

Within the Admin console it is possible to see the data that is placed on a queue.

  • In the Admin consolse you do:
  • Buses > YourBus > Destinations > Queue name > Queue points > QName@Server.YourBus > Messages > …

This shows a list of the messages that are available on the queue. You can either view the JMS details of the message but most important the the data send

Override Optimistic Lock and persist stale entity in Hibernate

In real time application, There could be a scenario to tell the hibernate not to allow concurrent update of an entity. Optimistic lock can be used to accomplish it, It never locks the underlying record in the DB rather it needs either Version or Timestamp column to determine whether the entity is up-to-date or stale.

 

@Column( name = "VERS", nullable = false )
@Version

private Long vers;

Version column is being updated automatically whenever entity is been udpated. Hibernate uses this version column value to check for stale. Second concurrent process which is updating this entity will receive OptimisticLockException/StaleObjectException.

If you want stale object to be updated  by any cause, use the following Spring AOP approach.Configure the following beans in your spring-beans.xml

 <bean id="retryingTransactionInterceptor">    
  <property name="order" value="1" />
  </bean>  
  <aop:config>     
   <aop:aspect id="retryingTransactionAspect" ref="retryingTransactionInterceptor">         
     <aop:pointcut  id="servicesWithRetryingTransactionAnnotation" expression="execution( * examples.service..*.*(..) ) 
     and @annotation(examples.annotation.RetryingTransaction)"/>         
     <aop:around method="retryOperation" pointcut-ref="servicesWithRetryingTransactionAnnotation"/>     
   </aop:aspect> 
  </aop:config>

 

 
package examples.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target( {
 ElementType.METHOD
} )
@Retention( RetentionPolicy.RUNTIME )
public @interface RetryingTransaction {
 int repeatCount() default 20;
}

 

@Transactional
 @RetryingTransaction
 public Test merge( Test test ) {
  return testDao.merge( test );
 }

 

package examples;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import javax.persistence.OptimisticLockException;
import javax.persistence.Version;
import org.aspectj.lang.ProceedingJoinPoint;
import org.hibernate.property.BasicPropertyAccessor;
import org.springframework.core.Ordered;
public class RetryingTransactionInterceptor implements Ordered {
 private static final int DEFAULT_MAX_RETRIES = 20;
 private int maxRetries = DEFAULT_MAX_RETRIES;
 private int order = 1;
 public void setMaxRetries( int maxRetries ) {
  this.maxRetries = maxRetries;
 }
 public int getOrder() {
  return this.order;
 }
 public void setOrder( int order ) {
  this.order = order;
 }
 public Object retryOperation( ProceedingJoinPoint pjp ) throws Throwable {
  int numAttempts = 0;
  Exception failureException = null;
  Object obj = null;
  Object arg1 = null;
  do {
   numAttempts++;
   try {
    Object[] obje = pjp.getArgs();
    arg1 = (Test) obje[ 0 ];
    obj = pjp.proceed();
    return obj;
   } catch ( RuntimeException re ) {
    failureException = re;
    System.out.println( "OptimisticLockException:"
      + ( (OptimisticLockException) re.getCause() ).getEntity() );
    incrementVersion( arg1 );
   }
  } while ( numAttempts <= this.maxRetries );
  throw failureException;
 }
 private Object incrementVersion( Object entityObject ) throws IllegalAccessException,
  InvocationTargetException, NoSuchMethodException {
  Object idValue = null;
  for ( Field field : entityObject.getClass().getDeclaredFields() ) {
   BasicPropertyAccessor basicGetter = new BasicPropertyAccessor();
   if ( field.getAnnotation( Version.class ) != null ) {
    System.out.println( "Id value:"
      + basicGetter.getGetter( entityObject.getClass(), field.getName() ).get(
       entityObject ) );
    idValue =
      basicGetter.getGetter( entityObject.getClass(), field.getName() ).get(
       entityObject );
    basicGetter.getSetter( entityObject.getClass(), field.getName() ).set(
     entityObject, (Long) idValue + 1, null );
    break;
   }
  }
  return idValue;
 }
}

Above code catches the OptimisticLock ,increase the version value and persist the stale
entity . You can also achieve it using simple update query too. It is up to
you to take correct decision.  

 

How to lazy load one to one related entity in hibernate JPA?

Hibernate does not support one-to-one lazy loading.

Work around is marking one-to-many relationship in parent end and one-to-one in child end.

In Parent

@OneToMany( mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.ALL )
private List<Child> childs;

In Child

@OneToOne( )
@JoinColumn( name = "child_id", referencedColumnName = "parent_id" )
private Parent parent;

Atomic Integer handles concurrency smartly & efficiently

Atomic integer is used to handle concurrency of increment and decrement operation smartly using a non-blocking algorithm.

Also it improves the execution time when compared to synchronized way of handling concurrency.

import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest {
 public static void main(String[] args) {
  AtomicInteger counter = new AtomicInteger(0);
  for(int i=0; i<50; i++) {
   Runnable runnable = new WorkerThread(counter);
   Thread t = new Thread(runnable);
   t.start();
  }
 }
}
class WorkerThread implements Runnable {
 AtomicInteger count = null;
 WorkerThread(AtomicInteger counter) {
  this.count = counter;
 }
 public void run() {
  int value = this.count.incrementAndGet();
  System.out.println(value);
 }
}

 Above problem spans 50 threads and does increment operation.

You can notice that it prints number between 1 and 50 without a duplicate value which ensures the concurrency.

Copy , Paste and Transfer files with remote desktop connection to and from your remote computer

1. Open Start>>Run and type mstsc

2. Now click on options and again click on Local Resources Tab.

3. Under Local Devices and Resources (in vista) ,click on more.. button. ( In Windows Xp ) you will see a checkbox as Local Drives

4. Check the Checkbox “drives” in the newly opened window in vista or check the checkbox Local Drives in Windows XP.

5. Click OK and connect to the remote computer now.

Sharing spring context between web apps

Load all jars part of server classpath loading which will be used to create the spring application context and can be shared/available between Web apps/EARs.

Web.xml (in all WEB apps)

<context-param>
  <param-name>parentContextKey</param-name>
  <param-value>beanRefFactory</param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 It looks for beanRefContext.xml part of classpath and a spring bean named “beanRefFactory”

beanRefContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 <bean id="beanRefFactory"
  class="org.springframework.context.support.ClassPathXmlApplicationContext">
  <constructor-arg >
    <list>
      <value>classpath*:spring-context.xml</value>
   </list> 
  </constructor-arg>
 </bean>
</beans>

spring-context.xml contains spring beans definition needed by the application and been loaded to create spring application context. This will be the parent application context.

Ensure that applicationContext.xml is placed in WEB-INF folder, used to create its own spring context which extends the parent application context created already. Define the spring beans specific to web modules here. if not, have dummy declaration given below.

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
</beans>

How to configure number of views in session – Perfomance tuning in JSF

JSF will maintain all its views & its state in HTTP session object if state saving method is server which will cause increased usage of memory. To avoid it, we can minimize the number of views stored in session which suits to the application need that can be defined in web.xml given below

<context-param>
 <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
 <param-value>server</param-value>
</context-param>

<context-param>
 <param-name>com.sun.faces.numberOfViewsInSession</param-name>
 <param-value>3</param-value>
</context-param>

<context-param>
 <param-name>com.sun.faces.numberOfLogicalViews</param-name>
 <param-value>10</param-value>
</context-param>

numberOfViewsInSession defines the number of view states (pages) to support back button operation.

numberOfLogicalViews defines the number of logical views (frames) that can present in a page.

Merging two persistence units

We can merge two persistence unit if both have same persistence-unit name. This can be done using persistence unit post processor.

Note: “default” is the PU name for both persistence1.xml and persistence2.xml given below.

persistence1.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="default">
    <class>examples.A</class>
    .
    .
    .
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>

persistence2.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="default">
    <class>samples.A</class>
    .
    .
    .
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>

2. Persistence post processor is used to merge all entities present in persistence1.xml & persistence2.xml and be

part of persistence unit manager.

package examples;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MergingPersistenceUnitPostProcessor
implements PersistenceUnitPostProcessor {
Map<String, List<String>> puiClasses = new HashMap<String, List<String>>();

public void postProcessPersistenceUnitInfo( MutablePersistenceUnitInfo pui ) {
List<String> classes = puiClasses.get( pui.getPersistenceUnitName() );
if ( classes == null ) {
classes = new ArrayList<String>();
puiClasses.put( pui.getPersistenceUnitName(), classes );
}
pui.getManagedClassNames().addAll( classes );
final List<String> names = pui.getManagedClassNames();
classes.addAll( pui.getManagedClassNames() );
}
}

3. Configure the merging persistence unit post processor in persistence unit manager.

    <bean    class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
    <bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="websphereDataSource" />
        <property name="persistenceUnitManager" ref="pum" />
        <property name="jpaVendorAdapter">
            <bean
                class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="database" value="ORACLE" />
                <property name="showSql" value="true" />
            </bean>
        </property>
    </bean>

    <bean id="pum" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
        <property name="persistenceXmlLocations">
            <list>
             <value>classpath*:META-INF/persistence1.xml</value>
             <value>classpath*:META-INF/persistence2.xml</value>
            </list>
        </property>
        <property name="defaultDataSource" ref="websphereDataSource"/>
        <property name="persistenceUnitPostProcessors">
            <bean class="examples.MergingPersistenceUnitPostProcessor"/>
        </property>
    </bean>