Tuesday 26 November 2013

Native Query Mapping to Transient Fields of Entity class

Native queries are often a problem when comes to mapping with customized Entity classes. Especially classes with transient fields. To overcome this problem we have a special annotation available in JPA since version 1.0.
                                      @SqlResultSetMapping
That will do the trick for you!
This type of mapping is called scalar mapping. The only problem in choosing JPA is, the community is very limited and very limited resources are available internet. For complex JPA queries, most struggle to find a solution.
So I am going to show an example of mixing entity and scalar mapping.

@ColumnResult(name = "progress") does the scalar mapping. Remember that when you write your native query, It must have a column with alias progress.

For example: select p.*, count(*) as progress from project p
We can also use @SqlResultSetMapping to map different Entities from one native query. I will show this example in my next post.

Thursday 31 October 2013

How to make java program run as a service/daemon in linux

Create a shell script as below
Now move this file to init.d location and issue update command to automatically start this as service when system reboots.

Thursday 17 October 2013

Connecting to Plesk Mysql through Command Line

Connecting to Plesk Mysql though Command Line:

     Connection to plesk mysql on ubuntu systems doesn't work in the usual way. Plesk mysql password is stored in a different location and its encrypted too. So we can't keyin the normal password through commandline unless you know the complete encrypted form.So, mysql -u root -p command is not going to work for you. Use the below command to connect to plesk mysql on ubuntu systems through command line. /etc/psa/.psa.shadow ( this is the place where your plesk mysql password is stored ). Use "cat" command to print the password right after -p.

   
  mysql -uadmin -p`cat /etc/psa/.psa.shadow`  

Sunday 6 October 2013

Install Android in NetBeans 7.3

Android in Netbeans 7.3

Please follow the below steps to install Android in NetBeans 7.3


Step1:

  Open Netbeans, Go to Tools->Plugins, and select Settings Tab, Click on Add button

Step 2:

  In URL field, paste the below url
         http://nbandroid.org/release72/updates/updates.xml     

  In Name Field, "Android"





Step 3: 

  Now go to Available Plugins tab and search for "Android", select android plugin and click Install button and restart NetBeans.

Step 4:

  Create new android project: 
      select "Android" category and "Android Project" from Projects section.



Step 5: Provide project Name, Location, package name, main activity and select android target platform.




 If Android SDK is not configured, Please go to android developer site and download the latest android sdk 
http://developer.android.com/sdk/index.html

and configure its path in netbeans ( Go to Tools->Options and select Android tab )



Thursday 3 October 2013

Glassfish 4 and Primeface 4.0.RC1 fileupload issues

Glassfish 4 and Primeface fileupload issues!

Maven dependencies:


<dependency>
    <groupId>org.primefaces</groupId>
    <artifactId>primefaces</artifactId>
    <version>4.0.RC1</version>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3</version>
</dependency>

uploadFile.getContents() method is not working in primeface 4.0.RC1 version. To get the file content, use the below code:


private byte[] getFileContents(InputStream in) {

byte[] bytes = null;
try {
   // 277*121, 292*170, 327*143, 586*340
   // write the inputStream to a FileOutputStream            
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   int read = 0;
   bytes = new byte[1024];

   while ((read = in.read(bytes)) != -1) {

bos.write(bytes, 0, read);
   }
   bytes = bos.toByteArray();
   in.close();
   in = null;
   bos.flush();
   bos.close();
   bos = null;
   logger.debug("New file created!");
} catch (IOException e) {
   System.out.println(e.getMessage());
}
return bytes;

}

getFileContents(getFile().getInputstream());

Tuesday 13 August 2013

Eclipselink Unique Key Constraint Log issue in glassfish server

You can find lot of people asking how to disable eclipselink unique key constraint violation logs in glassfish server, and there are lot of replies where none of them really works. The real solution lies in glassfish server configuration and not in eclipselink configuration. You can find lot of posts referring to eclipselink configuration where we have to add some property tags in persistence.xml file to switch off logs, but that wont stop the logs in glassfish.

<property name="eclipselink.logging.level" value="OFF" />
<property name="eclipselink.logging.parameters" value="false"/>        
<property name="eclipselink.target-server" value="SunAS9"/>
<property name="eclipselink.logging.exceptions" value="false"/>


By the time you catch exception, database constraint voilation would have already written to glassfish server log. So you have to switch off glassfish JTA server logs. But where and how to do it??? This blog entry has the answer for that.

Please follow the below steps :

  1. Log in to glassfish admin console
  2. Go to Configurations->server-config->Logger Settings
       



























 


   

    3. select javax.enterprise.resource.jta option and select SEVERE from log level combobox.

    4. Save and restart the server


Friday 2 August 2013

Spring security REST Authentication ( apikey or token based authentication )

Spring Security REST Authentication:
     One of the most searched terms on internet. Yes, I have searched a lot to accomplish a successful and well secured RESTful authentication. A lot of articles are available on internet regarding spring security, most of the articles are talking about the advanced technology behind it, but none of them explained the basic workflow of it. After searching for almost 2-3 weeks, Finally I have got a blog link for the entire code to achieve what I want, though, the explanation was not quite understandable. If you can understand just by looking at the code, you can copy paste the below code straight away. Users who prefer to understand the work flow nature of spring security REST authentication, please see the below picture. Its better to explain concepts using pictures rather than writing 1000 of words.

Let me list out the names of all classes we need

1)  RESTAuthenticationFilter.java
2)  RESTAuthenticationToken.java
3)  RESTCredentials.java
4)  UserSecurityServiceImpl.java
5)  UserSecurityService.java
6)  UserSecurityRepository.java
7)  UserSecurityRepositoryImpl.java
8)  RESTUser.java
9)  HMacShaPasswordEncoder.java
10) RESTDaoAuthenticationProvider.java
11) UserNotFoundException.java
12) NoRedirectStrategy.java



Above diagram shows the basic authentication flow of spring security. It all begins with a user who tries to login to a secured system. For example, lets take a simple url ( http://localhost/web-app/secured/payment) We are going to let only users who have the right permission/role to access secured urls. In that URL, "web-app" is the context-name and "/secured" is the relative url prefix mapped to DispatcherServlet.  Whevever a url request hits the server with "/secured" as its relative prefix, DispatcherServlet handles/process the request. Put the below code in web.xml to create url-mapping. 
Web.xml
Before this request is handed over to Spring controller and DispatcherServlet, we have to make sure the user has the rights/authority/permission to access this particular page. To bring authentication in to play, Enable spring security filter in web.xml and map spring security filter to this url-mapping (.../secured/...) in applicationContext-security.xml to intercept the secured url calls. Use the below code
web.xml
applicationContext-security.xml
The above tag applies spring security to all urls begins with "/secured" as their relative path. Now, no one can access secured urls without proper authentication. 
The above are the basic config tags that you must apply to implement any authentication scheme offered by spring. Lets take a look at some of the new bean instance references shown in applicationContext-security.xml (forbiddenEntryPoint and defaultRestAuthenticationFilter). 

forbiddenEntryPoint: When a user tries to access a protected url without proper authentication details, display forbidden message ( httpstatus 405 ).

defaultRestAuthenticationFilter: As shown in the diagram, its the entry point for all url requests. This is the place where all secured url authentication is validated. This filter extracts the token, signatures and salt parameter and validates the authentication details. If the url has all the required authentication details, then it is passed on to the next spring security filter chain and finally to the actual spring controller. In our case its "payment" controller. Take some time to understand the below code, you can find a few new bean references.
applicationContext-security.xml
Authentication Manager processes an authentication request. As shown in the diagram above, Authentication Filter passes an authentication object to Authentication Manager and finally returns a fully populated authentication object(including granted authorities ) if successful. http://static.springsource.org/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/authentication/AuthenticationManager.html. AuthenticationManager is a kind of wrapper class, It can support multiple AuthenticationProviders.

AuthenticationProvider is where the core authentication details validation logic is defined. It has retrieveUser(......) delegate method that takes username and  UsernamePasswordAuthenticationToken as params and returns UserDetails instance which includes GrantedAuthority if successful.

Saturday 27 July 2013

Java Automated Build Process With Hudson, Nexus, Git and Maven

Automated Build Process



I am going to explain the above picture work flow, then we will look at each technologies in detail.
Validate - validate the project
Test - Test the compiled source code using a suitable unit testing framework. Test code is separated from source code. Its not packaged and deployed with source code.
Package- Take the compiled source code and packaged in to a distributed format, such as       jar/war
Integration-test - process and deploy the package if necessary into an environment where integration tests can be run
Verify- Run and check to verify the package is valid or not
Install - Install the package in to the local repository
Deploy- Done in release environment. Deploy the package in to remote repository for sharing   with developers or other projects.



1. Developer has git installed in his local system. Lets assume that he has completed the task, he issues git commit command to commit his current changes in his local repository.

2. He, then issues git push command to push his changes to the remote repository which is a centralized repository server where the source code version is maintained. Clients connects to this centralized version control server to clone, pull, commit, push their changes. To learn more about git command please visit http://git-scm.com/documentation

3. Hudson(Continuous Integration) server. CI main focus is to notify the users who breaks the build due to erroneous code changes. Its possible that developers sometimes commit and push their changes without proper testing. So, CI connects to our central code repository server and picks the latest changes periodically and verify the changes by running test against them. It can be configured to notify all the developers in case if the build breaks. As shown in the diagram, It connects to the central repository to fetch the latest changes

4. Picks the latest changes and validate, compile, build, package, install in to the local repository or notify developers in case of any failure

5. If build and release phase is configured in the pom.xml file, It performs a release and deploy the new version in nexus repository management server.

6. This step is performed to automate the deployment of new version release in our web application server. In this step, We have to create a script file and configure it to execute after a successful release in pom.xml. This script file main focus is to connect to the nexus repository and download the latest release.

7. Once the download is complete, script file automatically deploy the distribution war in our web application server(glassfish opensource edition).


In java world, if you are a programmer who frequently working with server side applications, then an automated build process is very essential. In this post I will try to explain the work flow of an automated build system that we are currently following in our company. Automated build process of java application become very popular with the release of Maven technology. Without Maven its very tedious to build an automated system. Maven simplified the entire automated build process. Maven has its own life cycle to build an application phase by phase. It starts with


Compile- Compile the source code of the project







pom.xml is the heart of any maven project. Its the file where we can configure the build phases, what to include/exclude in a phase, how to filter unwanted dependencies, and most importantly how to maintain the dependencies. Managing dependencies version is one of the most important aspect of maven technology. In early days, developers has to taken care of the dependency jar file versions manually. But maven simply eliminated that need and provided a framework to handle all dependency files versions automatically. If we put "LATEST" as the version under "<version>" tag, maven automatically fetches the latest version of that dependency from maven central repository. Its that simple.

Sonatype Nexus: Nexus is a repository management standard. It helps the developers to share the artifacts with other projects.

Hudson: Continuous Integration, CI is a technology to automate the build process. It periodically check the code changes in source code repositories with the help of SCM tags and validate, compile, test, build and install the distribution package in local repository. It alerts the developers in case of any build cycle failure.

GIT: GIt is a distributed version control and source code management (SCM) system.

Sunday 21 July 2013

JVM Tuning

JVM is the heart of any java based applications. Most of the issues we face in our applications and servers are due to incorrect JVM settings and memory leaks. Memory leaks, well, we have no option we have to sit and debug the code. But the former is entirely a different task, Tuning a JVM is a dark art. You need to have complete knowledge about the JVM architecture. Also, tuning a JVM for a specific hardware is another headache. I have struggled a lot to configure our Glassfish server on Ubuntu with 16GB RAM. The default glassfish server JVM settings are not suitable for production use and that required some alteration. Now, after so much struggle, our server is running fine. So I thought this post would be helpful for some people who are struggling like me to configure JVM settings for different application servers. First we will learn about each segments of JVM in detail and in my next post I will show the glassfish jvm settings for production use.






-Xms: This jvm argument request the operating system to allocate the minimum amount of heap memory at start-up. i.e, -Xms1g allocates 1GB as the initial heap memory. It accepts m and g as the units

-Xmx: Set the maximum amount of JVM heap memory. OutOfMemoryException is thrown when memory goes beyond this level due to memory leaks or because of overload condition.


-XX:NewRatio: It defines the old/new generation ratio. In other words, this ratio defines the size of old(tenured) and new(eden) generation space. i.e, 

-XX:NewRatio=2 allocates 2:1 ratio for old to new generation.
If our max heap space is -Xmx=9g, then the calculation goes like this
2 / 3 * 9 = 6GB for old generation
1 / 3 * 9 = 3GB for new generation

-XX:PermSize: Allocates the initial permanent generation non heap size


-XX:MaxPermSize: Allocates the maximum permanent generation non heap size


-XX:SurvivorRatio: This parameter controls the size of two survivor spaces. i.e, -XX:SurvivorRatio=6 sets the ratio between each survivor space and eden to be 1:6, each survivor space will be one-eighth of the young generation.

UseAdaptiveSizePolicy parameter must be disabled, otherwise jvm ignore this parameter. If the size is too small, copying collection overflows directly in to tenured space. If the size is too large, they will be empty.

-server: jvm can be tuned for client or server machine. For example, If you download glassfish app server, by default, it is configured for client machine using -client parameter. But for production, we have to change this parameter to -server for better performance. -client and -server changes the garbage collection algorithms. -client uses Serial collector and -server uses Parallel collector algorithms. We will see GC algorithms in a short while.


How Garbage Collection works?

    All GC algorithms follows the same basic principle to deliver better memory utilization, though their implementation differs, some algorithms favor better throughput and some favor reduced latency. But their core principle is the same. When new instances/objects are created by the application, it is pushed in to Eden/young generation space, from there, algorithm detects whether its a short lived or long lived object, if its a long lived object, it is further moved on to survivor spaces and then on to tenured or old generation.
Finally when full GC occurs, this old object will be cleaned up if the object has no references. Short lived object stays in eden or in survivor spaces and cleaned up when short pause GC occurs.

Saturday 20 July 2013

Install UML in Netbeans 7.3

Netbeans supported UML in 6.7 release, but in later versions, I couldn't find any of the UML plugins. Anybody knows whats the reason behind that?. Fortunately I figured out a way to integrate UML with later versions of netbeans. I have tried this approach in Netbeans 7.3 and it worked for me.
But, unfortunately, Netbeans 7.3 unable to open the diagrams which I created earlier. I have created the project and a use case diagram successfully, saved it and closed the project, After some time, I reopened the project and tried to open the use case diagram, Nebeans couldn't open the diagram at all. Now I have to fall back to Netbeans 6.9 to continue with UML.
If anyone looking for UML in latest versions of Netbeans, Please follow the below steps. But its useless.

1) Star Netbeans

2) Go to Tools-> Plugins->Settings(tab)
     and click on Add button and enter the below URL     http://dlc.sun.com.edgesuite.net/netbeans/updates/6.9/uc/m1/dev/catalog.xml

then, Click ok

3) Go to Tools-> Plugins-> Available Plugins(tab)
     Search for "UML" in search textfield at the right side corner

4) Select the UML plugin and click on install and restart netbeans


Monday 15 July 2013

Cron Jobs Schedule Pattern

Cron job patterns:

To run a job at every hour of every day

   0 0 * * * *

To run a job at every 15 seconds

  */15 * * * * *

To run a job at every 30 min

   0 0/30 * * * *

To run a job at 6, 7 and 8 'o clock' of every day

   0 0 6-8 * * *

To run a job at 6, 6:30, 7, 7:30 and 8 'o clock' of every day

   0 0/30 6-8 * * *

To run only on week days between 6 and 8 'o clock'

   0 0 6-8 * * MON-FRI

To run on every christmas day at mid night

   0 0 0 25 12 ?

To run at midnight every day

   0 0 0 * * ?

Saturday 6 July 2013

Spring Task Execution And Scheduling

If your applications needs a single or batch of tasks to be executed in an asynchronous manner at some point in future, then what you are ultimately looking for is TaskExecuter implementations and TaskScheduler of spring framework.
TaskExecuter allows us to execute tasks in an asynchronous manner
TaskScheduler allows us to schedule a task to run at some point in future.
To know more about taskexecuter and taskscheduler visit http://static.springsource.org/spring/docs/3.0.x/reference/scheduling.html

Here we can see how to declare taskexecuter and taskscheduler in spring configuration file
and how to create a bean with cron job @Scheduled annotation to schedule the date and time of execution.

Spring configuration file

Now to schedule a job for every 20 minutes

Make sure to replace xxxxxxxxxxx of <context:component-scan base-package="xxxxxxxxxxx" /> with the package name of your ScheduleService class.

Now, lets analyse the attributes of task executer and scheduler.


<task:scheduler id="taskScheduler" pool-size="1"/>

pool-size="1": Here the value "1" indicates that only one task can be scheduled at a time. If you want one or more task to be scheduled in an asynchronous manner, increase its value. For example, to schedule 5 tasks at a time ( <task:scheduler id="taskScheduler" pool-size="5"/> )

<task:executor id="taskExecutor" pool-size="1" queue-capacity="2"/>

As in the case of scheduler, pool-size with value "1" indicates that only one task can be executed at a time. If you set value 1 to pool-size of scheduler and executer, it behaves in a synchronous manner.ie, only one task can be scheduled and only one task can be executed at a time. If you want to execute more tasks at a time, just increase the value of the pool-size. For example, If you want to execute 5 tasks at a time  
<task:executor id="taskExecutor" pool-size="5" queue-capacity="2"/>

<task:executor id="taskExecutor" pool-size="1" queue-capacity="2"/>

Capacity of TaskExecuter queue. Before an item is pushed to the pool, it checks the current capacity of the pool. If the pool is completely filled and busy, it will be pushed to the queue, and it remains there until the TaskExecuter finish running a task. Here the value "2" defines that only 2 tasks can be put in to the queue before it moves on to the pool.


Tuesday 2 July 2013

Avoid Duplicates in List

How to avoid duplicates in List 

There is no direct classes available in java to avoid duplicates. Use HashSet along with ArrayList to avoid duplicates

Monday 1 July 2013

/proc/kcore and rinetd occupies the entire hard disk space

We had a strange problem in ubuntu server. This happened without any warning, still don't know whats the reason for that. I logged in to the system and couldn't do anything...I was getting strange errors, and then I saw the hard disk space, it was 0...0 space left. It was shocking for me. We have around 2TB of hard disk space, then I checked the folders one by one...there was one folder named "proc" that occupied almost the entire 1.32TB of data and the rest by the /var/log folder.
I googled many times, and the result I got is this "proc/kcore" is a virtual file, it will not occupy any space. Its protected and you cannot delete that file also, then I restarted the system. After a quck reboot, system was normal...everything was working fine, after an hour and so I checked the disk space again,  boooooooooommmmmm...almost 50% occupied by "proc/kcore" file again. I couldn't find an answer for this. then I upgraded ubuntu 10.04 to 12.x.
After a successfull upgrade everything seemed to be normal. After 3-4 days, I checked the space again..booooooooooomm...35% of space gone....I checked the "proc/kcore" file this time...Fortunately this time it's not his fault. then I checked the /var/logs folder....too many logs..
After searching for a very long time, I found that there is a process called "RINETD" that creates too many logs.

I still couldn't find an answer for my 1'st problem.

But I managed to solve issues with RINETD process. To disable the logs just perform the below steps.

1) Stop rinetd process first

       service rinetd stop

2) Delete the log files from logs folder

       cd var/logs
       rm -R *

3) Open rinetd config file and disable the log output

     nano /etc/rinetd.conf

     To disable log, comment the following

      # Remove the comment from the line below to enable logging option.
      # logfile /var/log/rinetd.log

4) Restart the service again

      service rinetd restart 

Saturday 29 June 2013

Primefaces JSF Spring Web Application

Create java web application using primefaces

      I have been working with some of the web ui templates that makes my life easier for quite some time. I have tried vaadin, GWT kit, groovy and grails, primefaces etc. I would recommend Primefaces as the best option to design your template and pages. It's light weight compared to all other libraries. It has almost all UI components you are looking for. In my opinion, its the best ui component framework that works well with JSF and spring applications. Now it can be integrated with ROO applications also. primeface comes with built-in themes. If you want to apply twitter-bootstrap which is the most widely used themes in coming websites. Just add the maven dependency and enable the appropriate theme in web.xml. Its that simple.

Have a look at the comparison http://www.primefaces.org/whyprimefaces.html

Now we will see how to create a simple jsf-spring-prmeface maven web application.

Frameworks used:
  Spring 3.1.2.RELEASE
  JSF
  Spring security  3.1.0.RELEASE
  Primefaces

1) Since its a maven application, first get the required dependencies.

You can see that I have added bootstrap theme to my web application.

2) Now get the jsf dependencies. Most javaee containers supports built-in support for jsf. I have been working with glassfish server for quite some time. It has built in support for jsf. If you are using glassfish, add the below dependency.


servlet containers like tomcat needs the below dependencies

3) Add spring dependencies

If you want spring security, add the below dependencies too

4) Copy and paste the below contents to web.xml


5) Sample template jsf file
Clean and build your project. That's it!!!.


Thursday 27 June 2013

Getting JDBC Connection from EntityManager ( EclipseLink )

when things gets too complex, your hibernate/eclipselink jpa implementations won't help. You may need to access the underlying JDBC connection. Logic to extract a JDBC connection from JTA environment and non-JTA environment is not the same.
If you are using JTA datasource managed by the container, then you can get the connection directly from the JavaEE container Datasource. Just inject or lookup the datasource from JNDI. As long as you are with in a JTA trasactional context, the JDBC connection will be the same connection used by JPA.
If you are using non-JTA datasource, then you can still access the datasource from the javaEE container if you want a new connection. If you want the same connection used by JPA, then you can get it from JPAEntityManager interface.


Getting JDBC connection from JTA Datasource:

  First take a look at persistence.xml
  

  Now inject the Datasource bean in your java file
  

Getting JDBC connection from NON-JTA Datasource:

  JPA 2.0

  JPA 1.0

Wednesday 26 June 2013

Log4j Configuration

Steps to configure log4j in maven web application


Step: 1


   Add the required dependencies in pom.xml
                 

Step: 2

   Add log4j.xml in your application root folder.
   If you are using any IDE put log4j.xml in "src/main/resources". After compilation, it will be copied to "WEB-INF/classes" folder. Copy and paste the following contents in log4j.xml


I am using glassfish as the underlying server that's why the log folder relative path is "com.sun.aas.instanceRoot". For other servers, get the log folder path and replace that line. We are using RollingFileAppender, that enables us to create log files based on rolling policy. In other words, based on the date stamp it rolls at that time, 
            default is yyyy-MM-dd, (rolls at midnight)
See:http://logging.apache.org/log4j/companions/extras/apidocs/org/apache/log4j/rolling/TimeBasedRollingPolicy.html
So, instead of single file, It generates log files on daily basis.


Step: 3


    Add Log4jConfigListener in web.xml
    

To debug your java files
   
That's it! Now build and run the project.

Saturday 22 June 2013

Spring RESOURCE_LOCAL and JTA configurations

Spring RESOURCE_LOCAL(Local Transactions) and JTA(Global Transactions) configurations

So often people tend to make many mistakes with RESOURCE_LOCAL and JTA configurations, Without knowing the actual usage of tags, developers often mix these two configuration related tags. By doing so, spring instantiate unwanted beans in memory. So, I thought this blow would helps to developers to fix or create a proper RESOURCE_LOCAL and JTA xml configurations. I will also explain how to create proper JTA production configuration. Yes, JTA can be configured in different ways. But for production, Its better to handle the connections by the application container itself. So before start creating these configurations one has to have a complete knowledge of the xml tags used in these configurations.I would suggest you to read and understand all the topics discussed in http://static.springsource.org/spring/docs/2.0.x/reference/transaction.html

Global Transactions. Global transactions have a significant downside, in that code needs to use JTA, and JTA is a cumbersome API to use (partly due to its exception model). Furthermore, a JTAUserTransaction normally needs to be sourced from JNDI: meaning that we need to use both JNDIand JTA to use JTA. Obviously all use of global transactions limits the reusability of application code, as JTA is normally only available in an application server environment. Previously, the preferred way to use global transactions was via EJB CMT (Container Managed Transaction): CMT is a form of declarative transaction management (as distinguished from programmatic transaction management). EJB CMT removes the need for transaction-related JNDI lookups - although of course the use of EJB itself necessitates the use of JNDI. It removes most of the need (although not entirely) to write Java code to control transactions. The significant downside is that CMT is tied to JTA and an application server environment. Also, it is only available if one chooses to implement business logic in EJBs, or at least behind a transactional EJB facade. The negatives around EJB in general are so great that this is not an attractive proposition, especially in the face of compelling alternatives for declarative transaction management.
Local Transactions. Local transactions may be easier to use, but have significant disadvantages: they cannot work across multiple transactional resources. For example, code that manages transactions using a JDBC connection cannot run within a global JTA transaction. Another downside is that local transactions tend to be invasive to the programming model.
Spring resolves these problems. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments. The Spring Framework provides both declarative and programmatic transaction management. Declarative transaction management is preferred by most users, and is recommended in most cases.
With programmatic transaction management, developers work with the Spring Framework transaction abstraction, which can run over any underlying transaction infrastructure. With the preferred declarative model, developers typically write little or no code related to transaction management, and hence don't depend on the Spring Framework's transaction API (or indeed on any other transaction API).

We can use Hibernate/Eclipselink/Toplink,etc as the unerlying ORM technology, since I am familier with JPA 2 and its also the default implementation of glassfish I would always prefer to go with eclipselink for my web applications. Configured with Spring 3.1.2 release and mysql database and tested in glassfish 3.1.2.2 server.


Is an application server needed for transaction management?
The Spring Framework's transaction management support significantly changes traditional thinking as to when a J2EE application requires an application server.
In particular, you don't need an application server just to have declarative transactions via EJB. In fact, even if you have an application server with powerful JTA capabilities, you may well decide that the Spring Framework's declarative transactions offer more power and a much more productive programming model than EJB CMT.
Typically you need an application server's JTA capability only if you need to enlist multiple transactional resources, and for many applications being able to handle transactions across multiple resources isn't a requirement. For example, many high-end applications use a single, highly scalable database (such as Oracle 9i RAC). Standalone transaction managers such as Atomikos Transactions and JOTM are other options. (Of course you may need other application server capabilities such as JMS and JCA.)
The most important point is that with the Spring Framework you can choose when to scale your application up to a full-blown application server. Gone are the days when the only alternative to using EJB CMT or JTA was to write code using local transactions such as those on JDBC connections, and face a hefty rework if you ever needed that code to run within global, container-managed transactions. With the Spring Framework, only configuration needs to change so that your code doesn't have to.


Below you can see the JTA configuration with entityManagerFactory bean created from LocalContainerEntityManagerFactoryBean class


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">


<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="xxxx"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter" >
                <property name="showSql" value="false" />
                <property name="generateDdl" value="false" />
                <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
            </bean>
        </property>
        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.ReflectiveLoadTimeWeaver"/>
        </property>
    </bean>               
        
        <tx:annotation-driven /> 
        <tx:jta-transaction-manager/> 
        
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />


</beans>


JTA configuration with entityManagerFactory bean created from JNDI


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:jee="http://www.springframework.org/schema/jee"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
                http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">    
    
    <jee:jndi-lookup id="entityManagerFactory" jndi-name="jdbc/xxxx"/>
    <tx:annotation-driven /> 
    <tx:jta-transaction-manager/> 
        
    <bean
        class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
</beans>

If we are using jndi lookup in spring configuration file. Its necessary to place persistence-unit-ref in web.xml

web.xml
<persistence-unit-ref>
        <persistence-unit-ref-name>jdbc/xxxx</persistence-unit-ref-name>
        <persistence-unit-name>xxxx</persistence-unit-name>
    </persistence-unit-ref>

persistence.xml ( JTA )

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
  <persistence-unit name="xxxx" transaction-type="JTA">
    <jta-data-source>jdbc/xxxx</jta-data-source>
    <properties>
      <property name="eclipselink.jpa.uppercase-column-names" value="true"/>      
      <property name="eclipselink.cache.shared.default" value="false"/> 
      <property name="javax.persistence.lock.timeout" value="1000"/>     
      <property name="eclipselink.logging.level" value="SEVERE" />      
      <property name="eclipselink.target-server" value="SunAS9"/>
    </properties>
  </persistence-unit>
</persistence>


Below you can see the RESOURCE_LOCAL configuration with entityManagerFactory bean created from LocalContainerEntityManagerFactoryBean class

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">

    
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">        
        <property name="persistenceUnitName" value="xxxx"/>
        <property name="persistenceXmlLocation" value="classpath:META-INF/test-persistence.xml"/>
        <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
        <property name="jpaDialect">
            <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaDialect"/>
        </property>
        <property name="jpaPropertyMap">
            <props>
                <prop key="eclipselink.weaving">false</prop>
            </props>
        </property>

        <property name="loadTimeWeaver">
            <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver">
            </bean>
        </property>        
    </bean>

    <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
        <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />
        <property name="generateDdl" value="false"/>
        <property name="showSql" value="true"/>
    </bean>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${db.driver}" />
        <property name="url" value="${db.url}" />
        <property name="username" value="${db.username}" />
        <property name="password" value="${db.password}" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <tx:annotation-driven />

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

</beans>


persistence.xml ( RESOURCE_LOCAL )


<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
  <persistence-unit name="xxxx" transaction-type="RESOURCE_LOCAL">
    <class>xxxx</class>    
    <exclude-unlisted-classes>true</exclude-unlisted-classes>
    <properties/>
  </persistence-unit>
</persistence>

To create web applications I always use maven archetype that helps to automate the build process, dependency management, SCM, etc. If you find any difficulty in getting the required dependencies please use the below pom.xml file.
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jetty.version>6.1.4</jetty.version>
        <spring.version>3.1.2.RELEASE</spring.version>
        <spring.security.version>3.1.0.RELEASE</spring.security.version>
        <slf4j.version>1.5.10</slf4j.version>
        <java.version>1.6</java.version>
        <junit.version>4.10</junit.version>
        <mysql.connector.version>5.1.16</mysql.connector.version>
        <netbeans.hint.deploy.server>gfv3ee6</netbeans.hint.deploy.server>
    </properties>

    <dependencies>
     
         <dependency>
            <groupId>org.glassfish.extras</groupId>
            <artifactId>glassfish-embedded-all</artifactId>
            <version>3.2-b06</version>
            <scope>provided</scope>
        </dependency>  
               
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>0.9.8</version>
        </dependency>  
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>3.5</version>
        </dependency>
        <dependency>
            <groupId>org.primefaces.themes</groupId>
            <artifactId>all-themes</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2.2</version>
        </dependency>


        <!-- Spring Dependencies -->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
            <exclusions>
                <!-- Exclude Commons Logging in favor of SLF4j -->
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <type>jar</type>
            <scope>test</scope>
        </dependency>

        <!-- spring security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>${spring.security.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>${spring.security.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>${spring.security.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- DB Dependencies -->
        <!-- MySQL Connector -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.connector.version}</version>
            <type>jar</type>
            <scope>provided</scope>
        </dependency>
        <!-- Test Dependencies -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jettison</groupId>
            <artifactId>jettison</artifactId>
            <version>1.3.3</version>
        </dependency>
       
        <!-- logging -->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
            <exclusions>
                <exclusion>
                    <groupId>com.sun.jdmk</groupId>
                    <artifactId>jmxtools</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.sun.jmx</groupId>
                    <artifactId>jmxri</artifactId>
                </exclusion>
            </exclusions>
            <scope>compile</scope>
        </dependency>
<dependency>
            <groupId>log4j</groupId>
            <artifactId>apache-log4j-extras</artifactId>
            <version>1.1</version>
        </dependency>

    </dependencies>


I would recommend JTA configuration for production environment and RESOURCE_LOCAL for unit testing. With RESOURCE_LOCAL we have to take care of connection pooling and any change in connection pooling needs an application redepolyment. But with JTA, your application server provides connection pooling, transaction management and at run time we can change the connection pool settings without the need for application redeployment.