Pages

Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Using Spring Social To Update Status On Facebook, Twiiter and LinkedIn

This blog will cover the following topics:
  • OAuth dance overview
  • OAuth dance with Twitter, LinkedIn and Facebook
  • Using Spring Social templates
Spring Social’s main objective is to make it easy for Java applications to integrate with social network platforms, i.e. Facebook, Twitter, LinkedIn, etc.  It uses the same template technique that was used to make it very simple to work with JDBC or REST operations.  The templates I am referring to are FacebookTemplate.java, TwitterTemplate.java, and LinkedInTemplate.java.  Before you can use any of these templates, you need to provide an access token and/or access token secret.  What is an access token you ask?  Well, it all starts with OAuth dance.
OAuth Dance Overview
In a nutshell, OAuth allows you to share your private data reside on Facebook, Twitter, or LinkedIn with another site without having to hand out your user name and password.  OAuth protocol defines a series of steps to acquire an access token and these steps are known as the OAuth dance.  The OAuth dance is kind of like the “Texas Two Step” dance, it consists mainly of three steps (OAuth 1.0), which seem deceptively simple, but require time and dedication to master them.
Here is a short list of resources about OAuth dance:
The OAuth dance consists of three steps and the last step is when the access token is handed out.
  1. Establish request token
  2. Redirect user to authorization server – this is when user will enter his/her user name and password as well as granting authorizations for a website to access his/her data on his/her behalf
  3. Request access token

All major social network platforms implement OAuth protocol (some are on OAuth 1.0 and a few are on OAuth 2.0), which requires them to expose URLs for the above steps.  The beauty about a standard protocol is once you figure out how to work with one of these platforms, working with the next one is just a mattering of using the correct URLs.  OAuth libraries are widely available and there is a good chance you will find more than one  library for your favorite language.
OAuth Dance With Twitter, LinkedIn and Facebook
In my Java Spring powered web application,  I used a Java OAuth library called scribe.  One thing I really like about this library is that it provides examples to demonstrate how the OAuth dance works.  You just plugin the api key and api secret key into the sample code, and you are ready to go.   Another thing I like about scribe is that it has built in support for LinkedIn and Twitter, where the LinkedInApi.java and TwitterApi.java classes contain the appropriate request token and access token URLs.  Before showing the code I would like to mention a couple of important classes in scribe for dealing OAuth dance.  They are ServiceBuilder.java and OAuthService.java.  ServiceBuilder.java uses builder design pattern to build an implementation of OAuthService for a specific OAuth version (currently 1.0) implementation.  OAuthService.java interface defines a set of methods for the retrieval of request and access tokens and for the signing of HTTP requests.
The code below is for a use case where a user clicks on Sign In with LinkedIn”,  and this request goes to a Spring MVC  handler, which then initiates the request token process by asking SocialNetworkOAuthManager factory to create an instance of SocialNetworkOAuthManger for LinkedIn.  Once the request token is successfully retrieved from LinkedIn,  this handler returns a URL to LinkedIn OAuth authorization server, which displays a form to require user to enter user name and password, and to authorize access to his/her profile on LinkedIn.  After the authorization step is successful, LinkedIn OAuth server will redirect user to a provided callback URL “liEndOAuth.htm” with OAuth verifier token.  A handler for “liEndOAuth.htm” URL then goes and request  an access token and access token secret using the provided verifier token. That concludes the OAuth dance.
01@Controller
02@SessionAttributes({ "userLinkedInProfile", "linkedIn" })
03public class LinkedInController {
04   @RequestMapping(value = "/liStartOAuth.htm", method = RequestMethod.GET)
05   public ModelAndView startAuthentication() throws TwitterException {
06     SocialNetworkOAuthManager linkedInOAuthMgr =
07       SocialNetworkFactory.getLinkedInOAuthManager(
08         linkedInApiKeyPair.getApiKey(),
09         linkedInApiKeyPair.getApiKeySecret());
10 
11     ModelAndView mv = new ModelAndView("redirect:" + linkedInOAuthMgr.getAuthorizationURL());
12     mv.addObject("linkedIn", linkedInOAuthMgr);
13     return mv;
14  }
15 
16 @RequestMapping(value = "/liEndOAuth.htm", method = RequestMethod.GET)
17 public ModelAndView endAuthentication(
18      @RequestParam(value = "oauth_token", required = false) String oauth_token,
19      @RequestParam(value = "oauth_verifier") String oauth_verifier,
20      @ModelAttribute("linkedIn") SocialNetworkOAuthManager linkedInOAuthMgr) {
21 
22      AccessToken accessToken = linkedInOAuthMgr.getOAuthAccessToken(oauth_verifier);
23 
24      UserLinkedInProfile userLinkedInProfile = new UserLinkedInProfile();
25      userLinkedInProfile.setAccessToken(accessToken.getAccessCode());
26      userLinkedInProfile.setAccessTokenSecret(accessToken.getAccessSecretCode());
27 
28      ModelAndView mv = new ModelAndView("close");
29      mv.addObject("userLinkedInProfile", userLinkedInProfile);
30      return mv;
31 }
32}
The actual work of dealing OAuth dance is in the following classes: SocialNetworkOAuthManager.java, LinkedInOAuthManager.java and SocialNetworkFactory.java.
01public class SocialNetworkFactory {
02 public static SocialNetworkOAuthManager getLinkedInOAuthManager(String apiKey,
03                                            String apiSecretKey) {
04    return new LinkedInOAuthManager(apiKey, apiSecretKey);
05 }
06}
07 
08import org.scribe.builder.ServiceBuilder;
09import org.scribe.builder.api.LinkedInApi;
10import org.scribe.model.Token;
11import org.scribe.model.Verifier;
12import org.scribe.oauth.OAuthService;
13 
14public class LinkedInOAuthManager extends AbstractOAuthManager {
15 private static final String AUTHORIZE_URL = "https://api.linkedin.com/uas/oauth/authorize?oauth_token=";
16 
17 private OAuthService service;
18 private Token requestToken;
19 
20 public LinkedInOAuthManager(String apiKey, String apiSecretKey) {
21   super(apiKey, apiSecretKey);
22 
23   service = new ServiceBuilder()
24                 .provider(LinkedInApi.class)
25                 .apiKey(getApiKey())
26                 .apiSecret(getApiSecretKey())
27                 .callback("http://myserver.myapp.com:8080/myapp/liEndOAuth.htm")
28                 .build();
29 }
30 
31 public String getAuthorizationURL() {
32   requestToken = service.getRequestToken();
33   return AUTHORIZE_URL + requestToken.getToken();
34 }
35 
36 public AccessToken getOAuthAccessToken(String verifierCode) {
37   Verifier verifier = new Verifier(verifierCode);
38   Token token = service.getAccessToken(requestToken, verifier);
39   AccessToken accessToken = new AccessToken(token.getToken(), token.getSecret());
40 
41   return accessToken;
42 }
43}
As you can see, the scribe library makes it pretty easy to deal with OAuth dance.
Once the access token is available, it is just a matter of providing that to Spring Social
LinkedInTemplate.java. Below is an example of retrieving LinkedIn member profile URL and using TwitterTemplate.java to tweet.
1LinkedInTemplate linkedInTemplate = LinkedInTemplate(apiKey, apiSecret, accessToken, accessTokenSecret);
2linkedInTemplate.getProfileUrl();
3 
4TwitterTemplate twitterTemplate = TwitterTemplate(apiKey, apiSecret, accessToken, accessTokenSecret);
5twitterTemplate.updateStatus("This is amazing!!");
Unfortunately the LinkedInTemplate.java in Spring Social M1 doesn’t have a method to update network status. However it is not difficult to add such functionality yourself or see how that is done in this blog.
The code to implement the OAuth dance with Twitter is nearly identical to the code above so I won’t bore you with that code.  The Spring Social TwitterTemplate.java does have a method to send a tweet, so it is fairly trivial to send tweets.
The OAuth dance with Facebook is a bit different from LinkedIn and Twitter.  I guess because Facebook is now on OAuth 2.0.  There are two ways (that I know of) to get an access token from Facebook.  The first way is very simple, but it requires using Facebook JavaScript SDK and the second way is directly interacting with Facebook OAuth server via RESTful API.  In this blog, I will only go over the details of the first approach, which is based on the documentation at Facebook Developers site.
At a high level, FB JavaScript SDK provides an easy way using custom tag to display FB login/logout button and handles the redirection to their authorization server.  One important thing to know is once the authorization is successfully completed, the access token is saved in a cookie with name as fbs_.  This means the server side of your application can easily get its hand on the access token.  Spring Social comes with a handler method argument resolver (FacebookWebArgumentResolver.java) to extract the access token and user id out of the FB access token cookie for you.
Here is JavaScript code snippet.
1
2
5"true" perms="publish_stream" >
The “perms” attribute of the tag is a very important attribute because there is where you can specify what are the different resources that your application would like to have access to on behalf of users of your application.
The snippet of Java code below shows how to get to the access token and user id using Spring Social custom annotations @FacebookAccessToken and @FacebookUserId.
01@RequestMapping(value="/fbUpdateStatus.htm", method = RequestMethod.POST)
02public ModelAndView updateStatus(@RequestParam("status") String fbStatus,
03                                 @FacebookAccessToken String accessToken,
04                                 @FacebookUserId String userId) {
05   ModelAndView mv = null;
06   try {
07     FacebookTemplate facebook = new FacebookTemplate(accessToken);
08     facebook.updateStatus(fbStatus);
09 
10     mv = ModelAndViewUtil.buildSuccessfulAjaxStatus();
11   } catch (Exception e) {
12     mv = ModelAndViewUtil.buildFailedAjaxStatus(e.getMessage());
13   }
14 
15   return mv;
16}
NOTE: In order to get @FacebookAccessToken and @FacebookUserId annotations to work correctly, the FacebookWebArgumentResolver.java must be properly configured. There are two ways to do this, but the end goal is the same, which is to set FacebookWebArgumentResolver.java as one of the custom argument resolvers in AnnotationMethodHandlerAdapter.java.  The first way is if you are using the convenient tag, then pass an instance of FacebookWebArgumentResolver.java to AnnotationMethodHandlerAdapter inside a custom BeanPostProcessor.  The second way is don’t use the convenient tag and define both the DefaultAnnotationHandlerMapping bean and AnnotationMethodHandlerAdapter bean manually.  This way you can wire in an instance of FacebookWebArgumentResolver to the property customArgumentResolver of AnnotationMethodHandlerAdapter.
In my application I want to provide a small popup with a text box so a user can quickly send a tweet or send an update to his/her FB wall or send a network update on their LinkedIn member profile.  I stumbled upon qTip library, a tooltip plugin for jQuery framework and really like the functionality this library provides.  It makes it so easy to display a very professional looking tool tip.



More Here


Courtesy:http://fantastic.wordpress.com/2011/01/01/using-spring-social-to-update-status-on-facebook-twiiter-and-linkedin/#comment-663

Features of Spring (An Overview) Tutorial Java

Introduction:

One of the more exciting open-source Java frameworks that have gathered steam in recent past is Spring. Spring aims to minimize dependency of application components by providing a plug-in architecture. Because Spring links objects together instead of the objects linking themselves together, it is categorized as a ‘dependency injection’ or ‘inversion of control’ framework.

Spring’s object linking is defined in XML files, thus you can plug-in different components during runtime, or for different application configurations. This is particularly useful for applications that do unit testing or applications that deploy different configurations for different customers.

There are three primary types of dependency injection: setter-based, constructor-based, and interface-based injection. Spring supports both setter-based and constructor-based injection. As you will see later, this means Spring is able to create an object by passing objects references to its constructor and can modify the state of the object by calling its setter methods.

The terms ‘dependency injection’ and ‘inversion of control’ are often used interchangeably. Martin Fowler recently elaborated on the terminology, stating that dependency injection is a specific type of inversion of control. Specifically, dependency injection is a pattern where the responsibility for object creation and object linking is removed from the objects themselves and moved into a factory. Thus, dependency injection inverts the control for object creation and linking.



Though dependency injection is the basis of the Spring framework, Spring also provides a rich set of tools built on top of its core dependency injection functionality. Spring provides an MVC framework, support for several presentation frameworks, a transaction management framework, DAO support, support for several O/R mapping tools, and more.

This article is the first in a two-part series. I will introduce you to Spring’s basic dependency injection functionality and its JDBC toolkit. In the next article, I will introduce you to several other Spring features by building a simple Web-application using Spring’s MVC framework.

Injecting Dependency Using Factories
In this section I’ll show you an example of a class that you might want to refactor in order to use dependency injection. First, you’ll refactor the class programmatically, so that you can see how the pattern works without the use of a dependency injection framework. After that, you’ll explore how to inject dependencies using Spring.

The following example demonstrates a tight coupling between two classes (the DataProcessor class and the FileDataReader class).


class DataProcessor…
public Result processData() {
FileDataReader dataReader = new FileDataReader("/data/file1.data");
Data data = dataReader.readData();
return data.calculateResult();
}

client code…
DataProcessor fileDataProcessor = new DataProcessor();
Result result = fileDataProcessor.processData();

DataProcessor depends explicitly on FileDataReader. If we wanted to process data from another source (say a database) we would have to refactor the existing DataProcessor to operate on a more generic DataReader interface. One way to decouple the two is to push the creational responsibility for the DataReader out to the client code.

Here is the code, after refactoring:


class DataProcessor…
private DataReader dataReader;
public DataProcessor(DataReader reader) {
this.dataReader = reader;
}
public Result processData() {
Data data = dataReader.readData();
return data.calculateResult();
}

interface DataReader…
public Data readData();

client code…
FileDataReader dataReader = new FileDataReader("/data/file1.data");
DataProcessor fileDataProcessor = new DataProcessor(dataReader);
Result result = fileDataProcessor.processData();

Notice that the DataProcessor class no longer operates on FileDataReader, but rather on the DataReader interface that FileDataReader implements. By generalizing the interface, we’ve made DataProcessor more generic and reusable. The problem now is that any client code that wants to process data in a file has to create and link all the objects itself. Instead, we could inject the dependency between the DataProcessor and the DataReader using one or more factory classes.

One way would be as follows:


class DataProcessorFactory…
public static DataProcessor getFileDataProcessor() {
DataReader reader = new FileDataReader("/data/file1.data");;
DataProcessor dataProcessor = new DataProcessor(reader);
return dataProcessor;
}

client code…
DataProcessor fileDataProcessor = DataProcessorFactory.getFileDataProcessor();
Result result = fileDataProcessor.processData();

The DataProcessorFactory class is now responsible for creating and assembling our objects, and thus we have inverted control by way of dependency injection.



Spring as a Factory
Spring provides a core factory pattern, which eliminates the need to manually program factory objects (usually realized as singletons). It also, as the documentation explains, “allows you to decouple the configuration and specification of dependencies from your actual program logic.”

Developers who work on large software systems know that as a system grows the number of factory classes can become quite large. This is unfortunate, because most of these factory classes are fairly simple singletons that create objects and tie them together. There is a lot of code duplication because singletons make use of static methods and variables, which can’t be inherited. Thus, every singleton must reimplement the same basic structure.

The fundamental benefit of the Spring framework is its ability to act as a factory to create objects. Spring reads a schematic defined in an external configuration file, creates and wires the objects together using reflection, and then passes the objects back to you. Think of Spring as a factory that you don’t have to write any code for.

Here is what the example would look like if I were using Spring instead:


client code…
InputStream is = new FileInputStream("src/examples/spring/beans.xml");
BeanFactory factory = new XmlBeanFactory(is);

DataProcessor dataProcessor = (DataProcessor) factory.getBean("fileDataProcessor");
Result result = dataProcessor.processData();

As you can see, I created a factory using Spring’s XmlBeanFactory class, which reads an XML file that declaratively defines the classes that I want to create and link together. Like all bean factories in Spring, this class implements the BeanFactory interface.

Here is what the beans.xml file looks like:








/data/file1.data



The root element for a Spring configuration file is . This element contains one or more elements. A describes any Plain Old Java Object (POJO) in your application code.

The name attribute (id can also be used) provides a unique name for your bean. This is the name that your code will reference to retrieve beans from Spring. For example, in the above client code we accessed the DataProcessor bean by passing in fileDataProcessor. The class attribute tells Spring which class to instantiate. The singleton attribute tells Spring that this bean is a singleton, and thus Spring will always return the same instance of this bean. If singleton is set to false, Spring will generate a new bean for every request.

The sub-element represents an argument that should be passed into the constructor when Spring is generating the bean. If a constructor takes more than one argument, you may have to specify which argument in the XML file maps to which argument in the actual constructor using the “index” attribute. If an argument to a constructor or setter is another object, we can use the element to point to another bean definition in our configuration file. In the example, the fileDataProcessor bean references the fileDataReader bean. To pass a value into a constructor, we use the element. The element can be used to represent any built-in Java types such as int, long, String, boolean, etc. Spring will do all the work of converting the value to the appropriate type behind the scenes. If you need to inject a collection through a setter or constructor, Spring also has built-in support for defining Lists, Maps, Sets, and Properties collection types. Listing 1 is an example that is straight out of the Spring documentation. Setter vs. Constructor-based Injection The example on page 2 demonstrates how Spring can be used to do constructor-based injection. Spring also allows for setter-based injection. Here is an example of setter-based injection: my@email.address This code creates a Person object and calls the setEmail() method, passing in the string defined as a value. It is good practice to default your classes to being immutable until you have a reason to make them mutable. Constructor-based injection will allow you to take advantage of dependency-injection while still permitting immutability. If your classes are meant to be immutable, then it is probably best to stick with constructor-based injection. Autowiring Spring provides a mechanism for “autowiring” beans together. If there is one and only one bean of the type needed for reference by another bean, then Spring can auto-magically link them together for you. Here is an example:
I specified the autowire attribute on the fileDataProcessor bean to look for bean types that the object takes as a constructor. Because the constructor takes a FileDataReader, and I’ve only specified one, Spring will automatically link that one into our bean. If there is not exactly one bean defined of the type that I need (i.e. no bean or more than one bean), then Spring will throw an error.

This feature is meant to save you from having to explicitly type out the names of the beans that you reference. I personally favor explicitness in order to make the bean definitions more readable, thus I choose not to use Spring’s autowiring functionality, but you may find it useful.

ApplicationContext
Spring provides a richer mechanism for accessing beans called ApplicationContext. ApplicationContext, like XmlBeanFactory, implements Spring’s BeanFactory interface. ApplicationContext provides a few things above and beyond XmlBeanFactory. The Spring documentation recommends always using ApplicationContext unless you have memory usage restrictions, such as in a Java Applet.

One major advantage to ApplicationContext is that it can be loaded declaratively within the context of an application server. One way of doing this is in a Web application. Spring ties in to the standard J2EE mechanism for defining context parameters and application listeners in the Web deployment descriptor file (web.xml).

Here is what you need to define in web.xml:



contextConfigLocation/WEB-INF/applicationContext.xml/WEB-INF/anotherContext.xml



org.springframework.web.context.ContextLoaderListener


If you are using an older version of the Servlet API that doesn’t support listeners, you may alternatively have to use Spring’s ContextLoaderServlet in order to declaratively configure your ApplicationContext.

ApplicationContext is actually an interface in Spring. WebApplicationContext is a class that implements ApplicationContext and can be used in your Web applications. Here is how you access the ApplicationContext from within your Web application.


class ExampleServlet …
WebApplicationContext ctx =
WebApplicationContextUtils.getRequiredWebApplicationContext(
this.getServletContext());
DataProcessor fileDataProcessor = (DataProcessor) ctx.getBean("fileDataProcessor");



Loading Multiple XML Files
You can load multiple XML files into a BeanFactory using the ClassPathXmlApplicationContext class. This class takes a String[], of which each element points to an XML file.


String[] configFiles = new String[] { "examples/spring/spring.xml",
"examples/spring/spring-database.xml" };
BeanFactory factory = new ClassPathXmlApplicationContext(configFiles);

Wouldn’t it be nice if you could use dependency injection to define your BeanFactory itself? Actually, you can. Using an XML bean definition, you can create a ClassPathXmlApplicationContext and pass the XML file names into the constructor:








examples/spring/spring.xml examples/spring/spring-database.xml



This file can define one or more ApplicationContext beans and can even define a hierarchy of ApplicationContext beans. In order to obtain a reference to our ApplicationContext, Spring provides a Singleton called SingletonBeanFactoryLocator. The no-argument getInstance() method on this class will look for a file called beanRefFactory.xml in the root of the classpath. There is another getInstance() method that takes a String, which you can use to point to a different file. After obtaining a BeanFactoryLocator, you must obtain a BeanFactoryReference, which you use to obtain the BeanFactory calling the useBeanFactory() method and passing in the name designated to the bean in the XML file.


client code…
BeanFactoryLocator bfLocator = SingletonBeanFactoryLocator.getInstance();
BeanFactoryReference bfReference = bfLocator.useBeanFactory("examples.spring");
BeanFactory factory = bfReference.getFactory();
DataSource dataSource = (DataSource) factory.getBean("dataSource");



JDBC Support
As a consultant, I have worked with many different development teams, but I still can’t get over the fact that so many developers rewrite something similar to Listing 2 every single time they want to make a connection to the database.

If this block of code is spread throughout your code and you have seen and written it so many times that it is easy to regurgitate from memory, you probably aren’t writing reusable JDBC code.

The majority of this code deals with the creation and release of database resources and query execution. The only part of the code that is unique for each database interaction is the query string and the logic in the doSomethingWithResultSet() method. The resource-handling and query-executing code can easily be separated from your data-accessing code and encapsulated within a “template.” This template can then be provided with a query to execute on your behalf. A callback mechanism can be put in place for the template to call back the client code so that the client code can handle the ResultSet before the template cleans up the resources.

This type of separation of responsibilities makes for better OO design. Fortunately, thanks to Spring, you don’t have to implement this database-access template yourself. You can use Spring’s JdbcTemplate class to interact with a database through JDBC. Above and beyond the basic functionality we just discussed, JdbcTemplate provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.

Let’s look at an example of a DataReader that would read data from a database using JDBC:


class DatabaseDataReader implements DataReader…
private DataSource dataSource;
public DatabaseDataReader(DataSource dataSource) {
this.dataSource = dataSource;
}
public Data readData() {
JdbcTemplate template = new JdbcTemplate(dataSource);
int value1 = template
.queryForInt("select value1 from data where primary_key = 1");
int value2 = template
.queryForInt("select value2 from data where primary_key = 1");
return new Data(value1, value2);
}
}

The readData() method creates a JdbcTemplate, taking a java.sql.DataSource object as a parameter. The read data method makes two queries to the database to get the values that it needs to create a Data object. As you can see, each query makes use of the template’s queryForInt() method. This method returns the value of the query as a primitive int. After profiling your application, if we were to find out that making two database calls in this method was affecting your overall application performance, you could optimize your readData() method as follows:


class DatabaseDataReader implements DataReader…
public Data readData() {
JdbcTemplate template = new JdbcTemplate(dataSource);
List values = template
.queryForList("select value1, value2 from data where primary_key = 1");
Map valueMap = (Map) values.get(0);
int value1 = ((Integer) valueMap.get("value1")).intValue();
int value2 = ((Integer) valueMap.get("value2")).intValue();
return new Data(value1, value2);
}

Now you are using the queryForList() method, which returns a list of maps. Each entry in the list represents a row from the resulting query, and each entry in the map represents a column-name/cell-value pair.

If you had more complicated mapping to do, you could utilize Spring’s RowCallbackHandler:


class DatabaseDataReader implements DataReader, RowCallbackHandler…
public Data readData() {
JdbcTemplate template = new JdbcTemplate(dataSource);
template.query("select value1, value2 from data where primary_key = 1", this);
return new Data(value1, value2);
}
public void processRow(ResultSet resultSet) throws SQLException {
value1 = resultSet.getInt("value1");
value2 = resultSet.getInt("value2");
}

As you can see, the DatabaseDataReader class now implements RowCallbackHandler, which defines a processRow() method. When you call the query() method on JdbcTemplate you pass in a query string as well as a reference to a RowCallbackHandler. Because you are the callback handler, you pass in a reference to “this.” As Spring is going through its query workflow, it will make a call back to the processRow() method on your DatabaseDataReader object after it has created the database resources and executed the query. You will use the ResultSet object however you need to in the processRow() method, then when the processRow() method finishes running, the query method continues by releasing all necessary database resources.

As you may have noticed, you are passing a datasource in as an argument to the DataReader constructor. What a perfect place to use dependency injection! Here is what your bean definition would look like for a DataSource using mySQL and a database named “spring”:


More Here


Courtesy:http://amrendravimal.wordpress.com/2010/12/30/features-of-spring-an-overview/

Using Spring and Hibernate with WebSphere Application Server

Summary: If you’re considering using Spring or Hibernate with IBM® WebSphere® Application Server, this article explains how to configure these frameworks for various scenarios with WebSphere Application Server. This article is not an exhaustive review of either framework, but a critical reference to help you successfully implement such scenarios. (Updated with new security information.) This content is part of the IBM

Introduction

The Spring Framework, commonly referred to as Spring, is an open source project that aims to make the J2EE™ environment more accessible. Spring provides a framework for simple Java™ objects that enables them to make use of the J2EE container via wrapper classes and XML configuration. Spring’s objective is to deliver significant benefits to projects by increasing development productivity and runtime performance, while also improving test coverage and application quality.

Hibernate is an open source persistence and query framework that provides object-relational mapping of POJOs (Plain Old Java Objects) to relational database tables, as well as data query and retrieval capabilities.

While many organisations are interested in discovering what benefits they can obtain from using these frameworks, IBM wants customers who do use them to know that they can do so with WebSphere Application Server in a robust and reliable way. This article describes how these frameworks can be used with WebSphere Application Server, and explains best practices for a variety of use cases so that you can get started with Spring or Hibernate as quickly as possible.



Using Spring

Spring is generally described as a lightweight container environment, though it is probably 

more proper to describe it as a framework for simplifying development. The Spring Framework was developed by Interface21, based on publications by Rod Johnson on the dependency injection design pattern. Spring can be used either in standalone applications or with application servers. Its main concept is the use of dependency injection and aspect-oriented programming to simplify and smooth the transitions from development to testing to production.

One of the most often used scenarios involving Spring is to configure and drive business logic using simple Java bean classes. The Spring documentation should provide enough information to build an application using Spring beans; there is nothing WebSphere-specific about this. The following sections describe some of the usage scenarios for using Spring on WebSphere Application Server. Spring applications that are developed following the advice in this article should execute within a WebSphere Application Server or WebSphere Application Server Network Deployment environment with no difficulties.

Except where explicitly stated, the information presented here pertains to Versions 6.0.2.x, 6.1.x, and 7.0.x of WebSphere Application Server on all platforms.

Presentation tier considerations

This section describes considerations relating to the use of Spring in the Web-based presentation tier.

* Web MVC frameworks

Spring’s Web MVC framework is an alternative to other frameworks that have been around for some time. Web MVC frameworks delivered, used, and supported directly by WebSphere Application Server include JavaServer Faces (JSF) and Struts. Spring documentation describes how to integrate Spring with these Web frameworks. Use of any of these MVC is supported by WebSphere Application Server, although IBM will only provide product support for the frameworks shipped with WebSphere Application Server.
* Portlet MVC framework

Spring also provides a Portlet MVC framework (which mirrors the Spring Web MVC framework) and runs in both the WebSphere Portal V6.0 and the WebSphere Application Server V6.1 portlet containers. (See Spring Portlet MVC for an example set of Spring portlets.) Running portlets in the WebSphere Application Server V6.1 portlet container requires that an additional Web application be created to define the layout and aggregation of the portlets. Information on how to use the portlet aggregator tag library can be found in the WebSphere Application Server Information Center and in the article Introducing the portlet container. Using JSF in combination with portlets is a common practice for rendering. For information on how Spring, Hibernate, JSF, and WebSphere Portal can be combined together, see Configuring Hibernate, Spring, Portlets, and OpenInSessionViewFilter with IBM WebSphere Portal.

Data access considerations

This section describes considerations relating to the configuration of Spring beans that access data within a transaction.

The Spring framework essentially wraps Spring beans with a container-management layer that, in a J2EE environment, delegates to the underlying J2EE runtime. Following are descriptions of how Spring beans should be configured so that the Spring Framework properly delegates to (and integrates with) the WebSphere Application Server runtime.

* Accessing data sources configured in WebSphere Application Server

WebSphere Application Server manages the resources used within the application server execution environment. Spring applications that want to access resources, such as JDBC data sources, should utilize WebSphere-managed resources. To do this:
1. During development, the WAR module should be configured with a resource reference. For example:


jdbc/springdb
javax.sql.DataSource
Container
Shareable

2. For EJB JAR files, the same resource-ref should be declared in each EJB that needs to access the data source.
3. A data source proxy bean would then be declared within the Spring application configuration, which references a WebSphere-managed resource provider:








Accessing the data source through this proxy bean will cause the data source to be looked up using the module’s configured references, and hence be properly managed by WebSphere Application Server. Note that the jndiName property value matches the pattern java:comp/env/ concatenated with the res-ref-name declared in the resource-ref.

Alternatively, from Spring 2.5 onwards, this can be done using the approach. Notice how the jndiName property matches the actual value of the res-ref name declared in the resource-ref together with the resource-ref=”true” property:



4. The data source proxy bean may then be used by the Spring application as appropriate.
5. When the application is deployed to a WebSphere Application Server, a resource provider and resource data source must be configured in the normal fashion for use by the Spring application resource reference. The resource reference declared within the module’s deployment descriptor will be bound to the application server’s configured data source during deployment.
* Using JDBC native connections

Spring provides a mechanism for accessing native connections when various JDBC operations require interacting with the native JDBC resource. The Spring JdbcTemplate classes utilize this capability when a NativeJdbcExtractor class has been set on the JdbcTemplate class. Once a NativeJdbcExtractor class has been set, Spring always drills down to the native JDBC connection when used with WebSphere Application Server. This bypasses the following WebSphere quality of service functionality and benefits:
o Connection handle tracking and reassociation
o Connection sharing
o Involvement in transactions
o Connection pool management.

Another problem with this is the WebSphereNativeJdbcExtractor class depends on internal WebSphere adapter classes. These internal classes may differ by WebSphere Application Server version and may change in the future, thereby breaking applications that depend on this functionality.

Use of NativeJdbcExtractor class implementations (for example, WebSphereNativeJdbcExtractor) are not supported on WebSphere Application Server and you should avoid scenarios that require it. The alternative is to use the WebSphere Application Server WSCallHelper class to access non-standard vendor extensions for data sources.
* Using transactions with Spring

WebSphere Application Server provides a robust and scalable environment for transaction processing and for managing connections to resource providers. Connections to JDBC, JMS, and Java Connector resource adapters are managed by WebSphere Application Server regardless of whether or not a global transaction is being used; even in the absence of a global transaction there is always a runtime context within which all resource-provider connections are accessed. WebSphere Application Server refers to this runtime context as a local transaction containment (LTC) scope; there is always an LTC in the absence of a global transaction, and resource access is always managed by the runtime in the presence of either of a global transaction or an LTC. To ensure the integrity of transaction context management (and hence the proper management of transactional resources) WebSphere Application Server does not expose the javax.transaction.TransactionManager interface to applications or application frameworks deployed into WebSphere Application Server.

There are a number of ways to drive resource updates under transactional control in Spring, including both programmatic and declarative forms. The declarative forms have both Java annotation and XML descriptor forms. If you use Spring 2.5 with WebSphere Application Server V6.0.2.19 or V6.1.0.9 or later, you can take advantage of full support for Spring’s declarative transaction model. Spring 2.5 has a new PlatformTransactionManager class for WebSphere Application Server, called WebSphereUowTransactionManager, which takes advantage of WebSphere Application Server’s supported UOWManager interface for transaction context management. Managing transaction demarcation through WebSphere Application Server’s UOWManager class ensures that an appropriate global transaction or LTC context is always available when accessing a resource provider. However, earlier versions of Spring used internal WebSphere interfaces that compromised the ability of the Web and EJB containers to manage resources and are unsupported for application use. This could leave the container in an unknown state, possibly causing data corruption.

Declarative transaction demarcation in Spring 2.5 or later are supported in WebSphere Application Server using the following declaration for the WebSphere transaction support:



A Spring bean referencing this declaration would then use standard Spring dependency injection to use the transaction support, for example:





...



PROPAGATION_REQUIRED



Alternatively, from Spring 2.5 onwards, Spring’s AspectJ support can be utilised. In the following example, can be applied to various parts of the application. This indicates that all methods starting with “get” are PROPAGATION_REQUIRED and all methods starting with “set” are PROPAGATION_REQUIRES_NEW. All other methods use the default transaction settings.









The tag applies those settings to any executed operation defined within the class MyService.






Another alternative mechanism for declaring transaction settings is to use the Spring annotation-based transaction support. This requires the use of Java 5+, and therefore cannot be used with WebSphere Application Server V6.0.2.x.

Add the following to the Spring.xml configuration:



Any methods that require transactional attributes should then be marked with the @Transactional annotation:

@Transactional(readOnly = true)
public String getUserName()
{ ...

Be aware that the @Transactional annotation can only be used to annotate public methods.

The WebSphereUowTransactionManager supports each of the Spring transaction attributes:
o PROPAGATION_REQUIRED
o PROPAGATION_SUPPORTS
o PROPAGATION_MANDATORY
o PROPAGATION_REQUIRES_NEW
o PROPAGATION_NOT_SUPPORTED
o PROPAGATION_NEVER

For earlier versions of Spring that do not provide org.springframework.transaction.jta.WebSphereUowTransactionManager, and for versions of WebSphere Application Server prior to V6.0.2.19 or V6.1.0.9 that do not provide com.ibm.wsspi.uow.UOWManager, transaction support in WebSphere Application Server is available via this Spring configuration:





This configuration supports a restricted set of transaction attributes that does not include PROPAGATION_NOT_SUPPORTED and PROPAGATION_REQUIRES_NEW. The Spring class org.springframework.transaction.jta.WebSphereTransactionManagerFactoryBean, which also claims to provide PROPAGATION_NOT_SUPPORTED and PROPAGATION_REQUIRES_NEW capabilities, uses unsupported internal WebSphere Application Server interfaces and should not be used with WebSphere Application Server.
* Using Spring JMS

Just as with accessing JDBC data sources, Spring applications intended to access JMS destinations must ensure they use WebSphere-managed JMS resource providers. The same pattern of using a Spring JndiObjectFactoryBean as a proxy for a ConnectionFactory will ensure that JMS resources are properly managed.

For JMS message sending or synchronous JMS message receipt, JMSTemplates can be used. This includes the use of Spring’s dynamic destination resolution functionality both via JNDI and true dynamic resolution.

The following example shows the configuration of a resource reference for a ConnectionFactory. This reference is mapped during application deployment to point to a configured, managed ConnectionFactory stored in the application server’s JNDI namespace. The ConnectionFactory is required to perform messaging and should be injected into the Spring JMSTemplate.


jms/myCF
javax.jms.ConnectionFactory
Container
Shareable


There is now a defined JNDI name for your ConnectionFactory within the application that can be looked up and injected into the JMSTemplate:










...








At run time, the JMSTemplate can locate destinations based on either their JNDI name (as configured in an application resource reference) or through “dynamic resolution,” based on the administrative name of the destination configured in WebSphere Application Server; for example, for the JMS myQueue queue, bound to a JNDI reference of jms/myQueue:

JNDI resolution:
jmsTemplate.send("java:comp/env/jms/myQueue", messageCreator);

Dynamic resolution:
jmsTemplate.send("myQueue", messageCreator);

As an alternative to J2EE message-driven beans (MDBs), Spring provides a message-driven POJO model for processing inbound JMS messages asynchronously. Only a DefaultMessageListenerContainer class will manage messages from the JMS queue to the configured POJO that must be a javax.jms.MessageListener implementation.

In a WebSphere Application Server environment, you must also specify a WorkManagerTaskExecutor class, which means the DefaultMessageListenerContainer class will delegate to a server-managed thread pool. The DefaultMessageListenerContainer should also be configured with the server’s transaction management via the WebSphereUowTransactionManager, as described above.





















While this message-driven POJO model can be used, it is recommended that J2EE message-driven beans (MDBs) be used directly in WebSphere Application Server configurations that require workload management and/or high availability. Be aware that no other Spring JMS MessageListenerContainer types are supported, as they can start unmanaged threads and might also use JMS APIs that should not be called by applications in a Java EE environment.
* Using JPA with Spring

The EJB 3.0 specification defines the Java Persistence API (JPA) as the means for providing portable persistent Java entities. WebSphere Application Server V7 and the WebSphere Application Server V6.1 EJB 3 feature pack both provide implementations of EJB 3 and JPA; it is also possible to use the Apache OpenJPA implementation of JPA with WebSphere Application Server V6.1 (see Resources). When Spring is used in conjunction with a JPA implementation, you should use JPA directly rather than using Spring’s JPA helper classes (in the org.springframework.orm.jpa package).

WebSphere Application Server V6.1 and later supports JPA application-managed entity managers, which might have a transaction type of either JTA or resource-local. JTA entity manager uses the application server’s underlying JTA transaction support, for which transaction demarcation can be defined using either standard J2EE techniques or Spring’s declarative transaction model, as described above.

A data access object (DAO) that uses JPA is packaged with a persistence.xml that defines persistence context for the JPA EntityManager used by the application. For example, a persistence.xml for a JTA entity manager that uses the data source with a JNDI name “java:comp/env/jdbc/springdb” can be set up like this:



org.apache.openjpa.persistence.PersistenceProviderImpl
java:comp/env/jdbc/springdb








By setting the openjpa.TransactionMode and openjpa.ConnectionFactoryMode properties to “managed,” the JPA entity manager delegates management of transactions and connections to WebSphere Application Server. The DAO may use Spring’s declarative transaction demarcation as described above.

Annotation style injection of a JPA EntityManager is also possible. This is identical to standard JPA:

@PersistenceContext
private EntityManager em;

You need this XML code to turn on EntityManager injection in the Spring XML configuration:




Spring will create an EntityManager from any EntityManagerFactory defined in this XML file. If more than one exists, then it will fail. Use one (and only one) of these ways to create an EntityManagerFactory:
o Using Spring’s basic configuration





o Using Spring’s advanced configuration







Of course, the benefits of annotations and JPA are also available by using the pure EJB 3 support in WebSphere Application Server V7 and the WebSphere Application Server V6.1 EJB 3 Feature Pack. In either case, you can create an EntityManagerFactory using the JPA API, as shown below. This approach is not recommended for a non-EJB 3 environment, because any EntityManagers created might not be properly managed. However, when you do have an EJB 3 environment, you can use this approach to separate your Spring and JPA configurations.


* Spring EntityManagerFactory and JPA When using JPA, there is a conflict in the Spring EntityManagerFactory that requires configuring the entityManagerFactoryInterface property. This issue and its resolution are documented on the Spring Web site. * IBM JDK 6 WebSphere Application Server V7 runs on IBM JDK 6, which cannot be used with versions of the Spring framework prior to V2.5.5, due to a Spring problem documented within this JIRA. Spring security considerations Spring provides a security framework that differs significantly from the standard Java EE security framework. In some cases, this framework can rely on the underlying Java EE security runtime, and in other cases, the Spring security framework completely replaces it. The Spring implementation of an authentication provider enables integration with the container, but only at the level of calling a specific subroutine, org.springframework.web.filter.DelegatingFilterProxy, which is implemented as a servlet filter and configured in web.xml for the url pattern /* so that it gets called on every request. In terms of applicability to WebSphere Application Server authentication, see this article on the WebSphere Application Server authentication process and various options for extending or customizing WebSphere Application Server authentication before you proceed with any of the three common use patterns listed below — or any other implementation using org.springframework.web.filter.DelegatingFilterProxy: * The servlet filter is employed to replace J2EE container security. In this case, WebSphere Application Server J2EE security is not used. Either security is not enabled, or, if it is employed, no J2EE authorization constraint is defined in the web.xml. Spring security has its own security context (stored in the HTTP session for a user, by default) and uses GrantedAuthority objects to determine a user’s permissions on resources. The Spring security context is used for all authorization decisions. Since there is no Java EE security context, none of the WebSphere Application Server security features (such as, authorization, SSO integration with proxies, Java EE application SSO, SPNEGO integration, identity propagation to EJBs, services, databases, and so on) apply. * The servlet filter is used in conjunction with a Spring “pre-authenticated authentication provider,” which is conceptually similar to a WebSphere Application Server Trust Association (TAI). Here, J2EE security is enabled and there is a J2EE authorization constraint in the web.xml, so normal container authentication takes place. The pre-authenticated authentication provider extracts the username from the runtime and then calls isUserInRole() on a set of predefined roles. These roles are mapped to GrantedAuthority objects, and from then on the Spring security context is used. In this case, there is a valid Java EE security context and WebSphere Application Server security features are available — with the caveat that Spring-specific security features might or might not honor WebSphere Application Server security behavior. One such example is that it is possible to change the identity on a thread using WebSphere Application Server APIs, but that behavior may or may not be consistent when Spring security is employed. * The servlet filter is used in conjunction with a Spring JAAS authentication provider. As with the first case listed, WebSphere Application Server J2EE security is likely not even enabled, or, if it is, there is no J2EE authorization constraint defined in the web.xml. However, the actual task of authenticating the credentials obtained by the filter is delegated to the container by use of what is (from the WebSphere Application Server point of view) an application JAAS login. The login module and login configuration used are specific to the container in use, and Spring callback handlers are supplied to provide the username and password of the user. When the login is complete, the principals are obtained from the subject using loginContext().getSubject().getPrincipals(), and they are passed to a piece of code called an AuthorityGranter, which decides what GrantedAuthority objects to grant based on the Principal objects; be aware that the GrantedAuthority objects are not based on J2EE roles here. From here on, the Spring security context is used. However, from a WebSphere Application Server security perspective, the ltpaLoginModule is only a small part of the security runtime and this module is not designed to be called in isolation; rather, it is designed to be called as part of a login configuration to instantiate a JAAS subject. The actual instantiation of the JAAS subject is done by a second module, com.ibm.ws.security.server.lm.wsMapDefaultInboundLoginModule. It is only after this second login module is called that a WebSphere Application Server security context is created. As a result, because the WebSphere Application Server login module in question is not intended to be used this way, using it directly in the manner described has unpredictable consequences. Moreover, users implementing this approach have encountered serious performance issues, in addition to suffering from the same limitations mentioned in the first pattern. Of these, only the second use case listed above can be considered true “integration” because J2EE security is used for authentication and the Spring security context is used for subsequent authorization — although since the Spring security context is stored by default in the HTTP session (which is a security anti-pattern because HTTP session is not secure), you should steer clear of the default. If you choose to employ this pattern, you must to go to extra lengths to protect the session — which is not normally considered to be part of the security infrastructure; for example, you’ll need to protect the session cookie and should enable WebSphere Application Server session security integration. (See WebSphere Application Server V7 advanced security hardening for more.) Rather than storing Spring security context in an HTTP session, a better option would be to extend Spring to store the context in the JAAS subject instead, which will require additional custom development. As mentioned elsewhere in this article, this guidance should not be considered to be exhaustive. The points presented here with respect to Spring security do not constitute a discussion of all possible implications of using Spring security; rather, it is simply a list of issues that users have encountered from the inappropriate use of Spring security. While it might be possible to extend Spring security to provide reasonably secure integration with WebSphere Application Server and other Java EE applications that do not use Spring, you should always leverage the security implementation provided by WebSphere Application Server for applications running in WebSphere Application Server. Not only will this ensure robust and reliable security integration, but the security that is provided will be fully supported within WebSphere Application Server. One feature of Spring security that users seem to like is the authorization framework, which goes beyond what native Java EE authorization provides. If this is your primary reason for considering Spring security, you should investigate other, less disruptive options, such as IBM Tivoli Security Policy Manager or writing your own custom authorization, perhaps using your own access control lists. Using HttpSessionContextIntegrationFilter and forceEagerSessionCreation You should always use WebSphere Application Server security mechanisms to secure your WebSphere Application Server applications. If you use the Spring Security filter HttpSessionContextIntegrationFilter, however, here is a problem scenario you should watch for. HttpSessionContextIntegrationFilter executes after the call to the WebSphere Application Server server-side application code has been made; for example, the filter runs after a call to index.jsp has been made, which returns response data. As a result, the response will already have been committed when the call to create a session is reached in the Spring filter, and so the HTTP headers have already been returned. Since a Set-Cookie header must be added to the HTTP response, and the response has already been sent, a Java EE compliant container (such as WebSphere Application Server) might throw an IllegalStateException causing the Set-Cookie to fail. It has been observed that this exception is suppressed in at least some versions of Spring Security, which might lead to a NullPointerException later on — making it very difficult to determine exactly what happened. To avoid this problem, you can set the forceEagerSessionCreation option on the HttpSessionContextIntegrationFilter entry to true in your Spring configuration: Integration and management considerations * JMX and MBeans Spring JMX MBeans are supported on WebSphere Application Server V6.1 and later only when registered with WebSphere Application Server’s container manager MBeanServer. If no server property is specified, the MBeanExporter tries to automatically detect a running MBeanServer. When running an application in WebSphere Application Server, the Spring framework will therefore locate the container’s MBeanServer. You should not use MBeanServerFactory to instantiate an MBeanServer and then inject it into the MBeanExporter. Furthermore, the use of Spring’s ConnectorServerFactoryMBean or JMXConnectorServer to expose the local MBeanServer to clients by opening inbound JMX ports is not supported with WebSphere Application Server. Spring JMX MBeans are not supported on WebSphere Application Server prior to Version 6.1. * Registering Spring MBeans in WebSphere Application Server WebSphere Application Server MBeans are identified by a javax.management.ObjectName when they are registered that looks like this: WebSphere:cell=99T73GDNode01Cell,name=JmxTestBean,node=99T73GDNode01, process=server1,type=JmxTestBeanImpl This means that when they are de-registered, they need to be looked up with the same “fully qualified” name, rather than the simple name property of MBean. The best approach is to implement org.springframework.jmx.export.naming.ObjectNamingStrategy, which is an interface that encapsulates the creation of ObjectName instances and is used by the MBeanExporter to obtain ObjectNames when registering beans. An example is available on the Spring Framework forum. You can add the ObjectNamingStrategy instance to the bean that you register. This will ensure that the MBean is properly de-registered when the application is uninstalled. ... * MBeans ObjectNames and notifications Due to the use of a fully qualified ObjectName for MBeans in WebSphere Application Server, you are advised to fully define that ObjectName to use notifications. This JIRA enables the Spring bean name to be used instead and should provide a fix, but only if you are on the appropriate version of Spring. * System z multicall/unicall limitation As Spring doesn’t allow the specification of platform-specific fields in the MBean descriptor, Spring JMX will work on multi-SR servers on WebSphere Application Server V6.1, but you are restricted in your deployment options. WebSphere Application Server will default to the unicall strategy so that only one instance of the MBean (in one, indeterminate SR) will be asked to execute a request. This may be sufficient in some scenarios but it is more likely that an application will require the ability to declare a combination of multicall and unicall methods, and possibly result in aggregation logic. * Scheduling and thread pooling Spring provides a number of TaskExecutor classes that can be used for scheduling work. The only Spring TaskExecutor that is supported by WebSphere Application Server for executing work asynchronously is the Spring WorkManagerTaskExecutor class, which properly utilizes thread pools managed by WebSphere Application Server and delegates to a configured WorkManager. Other TaskExecutor implementations might start unmanaged threads. You can setup a WorkManager within the WebSphere Application Server administrative console by navigating to Resources => Asynchronous beans => Work managers . The JNDI name for the resource can then be used in the Spring config file as a workManagerName property to define a WorkManagerTaskExecutor. This example uses WebSphere Application Server’s DefaultWorkManager JNDI name or wm/default: * Classloaders Spring and WebSphere Application Server both use several open source projects and, unfortunately, the versions of the projects they have in common won’t always match. Spring dependencies should be packaged as part of the application, and the server should be setup as described below to avoid conflicts. Otherwise, the classloaders may not load the appropriate version either for the runtime or for the application. Usually, this will cause exceptions to appear in the log regarding version mismatches of classes, ClassCastExceptions, or java.lang.VerifyErrors. One example is the use of Jakarta Commons Logging. Configuring Jakarta Commons Logging (JCL) for application use, or utilizing a different version of JCL than is provided by the application server (for example, embedded with the application code) requires specialized configuration on WebSphere Application Server. See Integrating Jakarta Commons Logging for strategies on how to configure a deployed application to use an embedded version of commonly used technologies. Keep an eye on the support Web site for updates on how to configure embedded JCL on WebSphere Application Server V6.x products. This is just one example of conflicts. Others might include application use of JDOM or specific versions of JavaMail. Replacement of WebSphere Application Server’s JAR files with these or other packages with later or different versions is not supported. Another classloader problem that may plague Spring users on WebSphere Application Server is the way Spring loads resources. Resources can include things such as message bundles, and with the classloader hierarchy and various policies for locating resources within the hierarchy, it is possible for resources using a common name to be found in an unintended location. The WebSphere Application Server classloader viewer can be used to help resolve this problem. The combination of this and other versions of common libraries may require that the application rename resources to a unique name. The example explained by James Estes on the Spring forum contains an EJB project and a Web project packaged into an EAR file. The solution described is to add the spring.jar file into both the WEB-INF/lib and the top level of the EAR, then set the classloader policy for the WEB project to PARENT LAST so that it finds the version in WEB-INF/lib first. The EJB project uses the version in the EAR. Design considerations Some of the infrastructure services provided by the Spring Framework replicate services provided by a standards-based application server runtime. Furthermore, the abstraction of the Spring framework infrastructure from the underlying J2EE application server necessarily weakens the integration with application server runtime qualities of service, such as security, workload management, and high availability. As a result, using the Spring Framework in applications deployed into the WebSphere Application Server must be carefully considered during application design to avoid negating any of the qualities of service provided by WebSphere Application Server. Where no other recommendation is made, directly using the services provided by WebSphere Application Server is preferred in order to develop applications based on open standards and ensure future flexibility in deployment. * Unmanaged threads There are some Spring scenarios that can lead to unmanaged thread creation. Unmanaged threads are unknown to WebSphere Application Server and do not have access to Java EE contextual information. In addition, they can use resources without WebSphere Application Server knowing about it, exist without an administrator’s ability to control their number and resource usage, and impede on the application server’s ability to gracefully shutdown or recover resources from failure. Applications should avoid any scenario that causes unmanaged threads to be started, such as: o registerShutdownHook Avoid using the Spring AbstractApplicationContext or one of its subclasses. There is a public method, registerShutdownHook, that creates a thread and registers it with the Java VM to run on shutdown to close the ApplicationContext. Applications can avoid this by utilizing the normal lifecycle notices they receive from the WebSphere container to explicitly call close on the ApplicationContext. o WeakReferenceMonitor Spring provides convenience classes for simplified development of EJB components, but be aware that these convenience classes spawn off an unmanaged thread, used by the WeakReferenceMonitor, for cleanup purposes. * Scheduling Spring provides (or integrates with) a number of scheduling packages, but the only Spring scheduling package that works with threads managed by WebSphere Application Server is the CommonJ WorkManager. Other packages, such as quartz and the JDK Timer, start unmanaged threads and should be avoided. Back to top Using Hibernate Hibernate is an open source persistence framework for POJOs, providing object-relational mapping of POJOs to relational database tables using XML configuration files. The Hibernate framework is a data access abstraction layer that is called by your application for data persistence. Additionally, Hibernate provides for the mapping from Java classes to database tables (and from Java data types to SQL data types), as well as data query and retrieval capabilities. Hibernate generates the requisite SQL calls and also takes care of result set handling and object conversion. Hibernate, like OpenJPA, implements the Java Persistence APIs (JPA) specification, which is a mandatory part of Java EE 5. (See Resources for developerWorks articles on using Hibernate.) Usage scenarios The following scenarios describe some of the possible scenarios for how to use Hibernate with WebSphere Application Server and WebSphere stack products. These are only example scenarios and should not be considered recommended scenarios. * Use a WebSphere Application Server data source In order for Hibernate to get database connections from WebSphere Application Server, it must use a resource reference, as mandated by the Java EE (formerly known as J2EE) specification. This ensures WebSphere Application Server can provide the correct behavior for connection pooling, transaction semantics, and isolation levels. Hibernate is configured to retrieve a data source from WebSphere Application Server by setting the hibernate.connection.datasource property (defined in the Hibernate configuration file) to refer to a resource reference (for example, java:comp/env/jdbc/myDSRef) defined in the module’s deployment descriptor. For example: java:/comp/env/jdbc/myDSRef Java EE resource references for Web applications are defined at the WAR file level, which means all servlets and Java classes within the container share the resource reference. Inside of an EJB module, resource references are defined on the individual EJB components. This means that, if many EJB components use the same Hibernate configuration, each EJB must define the same reference name on each EJB component. This can lead to complications that will be discussed a bit later. Once a data source is configured, one of the next steps to ensure that Hibernate works correctly is to properly configure transaction support. * Transaction strategy configuration Hibernate requires the configuration of two essential pieces in order to properly run with transactions. The first, hibernate.transaction.factory_class, defines transactional control and the second, hibernate.transaction.manager_lookup_class, defines the mechanism for registration of transaction synchronization so the persistence manager is notified at transaction end when it needs to synchronize changes with the database. For transactional control, both container-managed and bean-managed configurations are supported. The following properties must be set in Hibernate.cfg.xml when using Hibernate with WebSphere Application Server: o for container-managed transactions: org.hibernate.transaction.CMTTransactionFactory org.hibernate.transaction.WebSphereExtendedJTATransactionLookup o for bean-managed transactions: org.hibernate.transaction.JTATransactionFactory org.hibernate.transaction.WebSphereExtendedJTATransactionLookup java:comp/UserTransaction
The jta.UserTransaction property configures the factory class to obtain an instance of a UserTransaction object instance from the WebSphere container.

The hibernate.transaction.manager_lookup_class property is supported on the WebSphere platform by WebSphere Application Server V6.x and later, and on WebSphere Business Integration Server Foundation V5.1 and later. This property configures Hibernate to use the ExtendedJTATransaction interface, which was introduced in WebSphere Business Integration Server Foundation V5.1 and WebSphere Application Server V6.0. The WebSphere ExtendedJTATransaction interface establishes a pattern that is formalized in Java EE 5 via the JTA 1.1 specification.
* Unsupported transaction configurations

The Hibernate documentation describes transaction strategy configurations for running on WebSphere Application Server Versions 4 and 5 products; however, these configurations use internal WebSphere interfaces and are not supported on those earlier versions. The only supported transaction configuration of Hibernate is described above, which means, as stated earlier, Hibernate usage is only supported on WebSphere Business Integration Server Foundation V5.1 and on WebSphere Application Server Version 6.x and later.
* Hibernate’s usage patterns within a WebSphere Application Server environment

Hibernate’s session-per-request and long conversation patterns are both available when using Hibernate with WebSphere Application Server. Customers must choose which is appropriate for their application, though it is our opinion that session-per-request offers better scalability.
o Multiple isolation levels

Sharable connections provide a performance improvement in WebSphere Application Server by enabling multiple resource users to share existing connections. However, if sharable connections and multiple isolation levels are both necessary, then define a separate resource-ref and Hibernate session-factory for each connection configuration. It is not possible to change the isolation level of a shared connection. Therefore, it is also not possible to use the hibernate.connection.isolation property to set the isolation level on a sharable connection. See Sharing connections in WebSphere Application Server V5 for more information on policies and constraints on connection sharing. (Although this article generally pertains to all shared connection use on WebSphere Application Server V5, the connection sharing advice still follows for Hibernate running on V6.x.)
o Web applications

Hibernate long conversation sessions can be used and stored in HttpSession objects; however, a Hibernate session holds active instances and, therefore, storing it in an HttpSession may not be a scalable pattern since sessions may need to be serialized or replicated to additional cluster members. It is better to use HttpSession to store disconnected objects (as long as they are small, meaning 10KB to 50KB) and re-associate them with a new Hibernate session when an update is needed. This is because HttpSession is best used for bookmarking and not caching. A discussion on how to minimize memory use in HttpSession is contained in Improving HttpSession Performance with Smart Serialization. Instead of using HttpSession as a cache, consider using a WebSphere data caching technology like ObjectGrid or DistributedObjectCache, as described in the next section.

For best practices on high performing and scalable applications, the book Performance Analysis for Java Websites is strongly recommended.

At the time of publication, the behavior of Hibernate’s cluster aware caches in conjunction with WebSphere Application Server has not been determined; therefore, it is not yet determined whether or not their use is supported and we will not discuss them further. As a result, customers requiring a distributed cache should consider creating a class that implements org.hibernate.cache.CacheProvider using the property hibernate.cache.provider_class, which employs one of the two distributed cache implementations in WebSphere.

* Integrating a second-level cache

A Hibernate session represents a scoping for a unit of work. The Session interface manages persistence during the lifecycle of a Hibernate session. Generally, it does this by maintaining awareness or state of the mapped entity class instances it is responsible for by keeping a first-level cache of instances, valid for a single thread. The cache goes away when the unit of work (session) is completed. A second-level cache also can be configured to be shared among all sessions of the SessionFactory, including across a cluster. Be aware that caching in Hibernate raises issues that will need to be addressed. First, no effort is made to ensure the cache is consistent, either with external changes to the database or across a cluster (unless using a cluster aware cache). Second, other layers (such as the database) may already cache, minimizing the value of a Hibernate cache. These issues must be carefully considered in the application design, but they are beyond the scope of this article.

Hibernate comes with several pre-configured caches. You can find information on them in the Hibernate Cache documentation pages. For read-only data, one of the in-memory caches might be enough. However, when the application is clustered and a cluster aware cache is needed, the local read-only caches are not enough. If a distributed cache is desired, we recommend using one of the WebSphere-provided distributed cache implementations. These can be used as a second level cache with Hibernate:
o The DistributedMap/DistributedObjectCache interfaces provide distributed cache support the WebSphere v6.x product family. See Using the DistributedMap and DistributedObjectCache interfaces for the dynamic cache for more information.
o ObjectGrid, available as part of the WebSphere Extended Deployment product, provides extensible object caching support. See ObjectGrid for more information.
* Using Hibernate in WebSphere Enterprise Service Bus and WebSphere Process Server

WebSphere Process Server and WebSphere Enterprise Service Bus (ESB) rely on the Service Component Architecture (SCA) and Service Data Objects (SDO) as an assembly and programming model for SOA. (See Resources to learn more about SCA and SDO.) SCA components are not Java EE components, so they do not have resource references, but rely instead on services and adapters to connect to systems. Resource references cannot be used when building Java SCA components; therefore, Hibernate cannot be used directly by an SCA component.

In this case, Hibernate persistence should be hidden behind some kind of facade. There are two alternatives:
o A local EJB session facade is created to wrap Hibernate persistence. The session facade provides adapter logic to map Hibernate entity POJOs to Service Data Objects and back. An integration developer can then use an EJB import to invoke the session facade, and invoke it in a tightly coupled fashion with corresponding Qualities of Service (QoS).
o An EJB Web service session facade is created to wrap Hibernate persistence. An integration developer can then use a Web service import to invoke the Web service for persistence. This gets around having to build POJO to SDO converters, since at the current time SCA only uses SDO for data types. Figure 1 illustrates a business process using both patterns, though the details of the process are beyond the scope of this article.

Figure 1. Sample business process
Figure 1. Sample business process
* Hibernate JPA API on WebSphere Application Server V6.1

Hibernate’s JPA support provides for JPA standard persistence and is a good alternative to the proprietary Hibernate APIs. Hibernate’s JPA implementation requires a Java SE 5 based runtime, and therefore only runs on WebSphere Application Server V6.1 or later. At the time of publication, Hibernate’s JPA support does not run on WebSphere System z or iSeries platforms. The Hibernate documentation describes how to package and deploy applications using Hibernate’s JPA implementation.
* Non-interoperable / Non-portable function

Section 3.2.4.2 in the JPA specification describes a scenario that is likely to cause interoperability and potential portability problems. This has to do with the combination of the use of lazy loading (that is, @Basic(fetch=LAZY)) and detached objects. When merging a detached object back into a session, JPA will examine the object and update the data store with any changed values. However, data objects are simple POJOs. If part of the POJO state wasn’t loaded when it was detached, it can appear to be changed when it is merged back in. To get this to work correctly, vendors must implement serialization techniques specific to their runtime. This is not interoperable and the semantics may not be portable either.

Back to top

Product and customer technical support

An area of reasonable concern for users is support of projects using open source and the impact of that usage upon a vendor’s support for its licensed products. IBM recognizes that some customers may desire to use non-IBM frameworks in conjunction with IBM WebSphere Application Server and is providing information to customers that may promote the creation of the most reliable operating environment for IBM WebSphere Application Server. IBM considers open source code and application frameworks installed by customers, either bundled as part of the application or as shared libraries, to be part of application code. By carefully utilizing this information when using open source projects, customers may use IBM products with a higher degree of confidence that they may have continued access to IBM product and technical support. If a problem is encountered when using these frameworks with WebSphere products, IBM will make reasonable efforts to ensure the problem does not lie with the WebSphere product.

It is expected that customers may safely use frameworks such as Spring and Hibernate on IBM products by observing the suggestions of this article and understanding a few key points:

* Customers must ensure that they only use those frameworks in ways that are allowed by WebSphere Application Server. In particular, this means that frameworks should not be used when they use internal product interfaces — unfortunately many open source frameworks do this when not configured carefully. Customers should avoid scenarios clearly documented as things to avoid on WebSphere.
* For open source frameworks, customers should ensure they understand and have access to matching source code and binaries for the framework they are using with WebSphere Application Server.
* Customers are encouraged to obtain corrective service for the frameworks from the open source community or from partners working with the open source community.

For more details on IBM support and policy please refer to the IBM Support Handbook and WebSphere Application Server Support Statement.

Although following the suggested practices of this article will help you enhance your experience when using WebSphere Application Servers in an open source environment, it is not an all inclusive list of ways in which an open source component may impact WebSphere Application Server operation or the operation of other components. Users of open source code are urged to review the specifications of all components to avoid licensing, support, and technical issues.

Throughout this article, the terms “support” or “supported” indicates that the usage being described uses only IBM documented functionality. The authors have done their best to provide advice on how to configure and use these frameworks to ensure that their usage is consistent with documented product behavior, but this article is neither an endorsement nor a statement of support for Spring or Hibernate.

More Here


Courtesy:http://skysoftarchive.wordpress.com/2010/11/21/using-spring-and-hibernate-with-websphere-application-server/