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

25.12.11

Spring Message Listener Container

Chapter 19. JMS (Java Message Service)

19.2.4. Message Listener Containers

One of the most common uses of JMS messages in the EJB world is to drive message-driven beans (MDBs). Spring offers a solution to create message-driven POJOs (MDPs) in a way that does not tie a user to an EJB container. (See the section entitled Section 19.4.2, “Asynchronous Reception - Message-Driven POJOs” for detailed coverage of Spring's MDP support.)

A message listener container is used to receive messages from a JMS message queue and drive the MessageListener that is injected into it. The listener container is responsible for all threading of message reception and dispatches into the listener for processing. A message listener container is the intermediary between an MDP and a messaging provider, and takes care of registering to receive messages, participating in transactions, resource acquisition and release, exception conversion and suchlike. This allows you as an application developer to write the (possibly complex) business logic associated with receiving a message (and possibly responding to it), and delegates boilerplate JMS infrastructure concerns to the framework.

There are three standard JMS message listener containers packaged with Spring, each with its specialised feature set.

19.2.4.1. SimpleMessageListenerContainer

This message listener container is the simplest of the three standard flavors. It simply creates a fixed number of JMS sessions at startup and uses them throughout the lifespan of the container. This container doesn't allow for dynamic adaption to runtime demands or participate in externally managed transactions. However, it does have the fewest requirements on the JMS provider: This listener container only requires simple JMS API compliance.

19.2.4.2. DefaultMessageListenerContainer

This message listener container is the one used in most cases. In contrast to SimpleMessageListenerContainer, this container variant does allow for dynamic adaption to runtime demands and is able to participate in externally managed transactions. Each received message is registered with an XA transaction (when configured with a JtaTransactionManager); processing can take advantage of XA transation semantics. This listener container strikes a good balance between low requirements on the JMS provider and good functionality including transaction participation.

19.2.4.3. ServerSessionMessageListenerContainer

This listener container leverages the JMS ServerSessionPool SPI to allow for dynamic management of JMS sessions. The use of this variety of message listener container enables the provider to perform dynamic runtime tuning but, at the expense of requiring the JMS provider to support the ServerSessionPool SPI. If there is no need for provider-driven runtime tuning, look at the DefaultMessageListenerContainer or theSimpleMessageListenerContainer instead.

27.10.10

Aspect Oriented Programming with Spring AspectJ and Maven

http://www.javacodegeeks.com/2010/07/aspect-oriented-programming-with-spring.html

 

Spring framework comes with AOPsupport. In fact, as stated in Spring reference documentation,
“One of the key components of Spring is the AOP framework. While the Spring IoC container does not depend on AOP, meaning you do not need to use AOP if you don't want to, AOP complements Spring IoC to provide a very capable middleware solution. AOP is used in the Spring Framework to...

  • ... provide declarative enterprise services, especially as a replacement for EJB declarative services. The most important such service is declarative transaction management.
  • ... allow users to implement custom aspects, complementing their use of OOP with AOP.”

Nevertheless Spring AOP framework comes with certain limitations in comparison to a complete AOP implementation, such as AspectJ. The most common problems people encounter while working with Spring AOP framework derive from the fact that Spring AOPis “proxy – based”. In other words when a bean is used as a dependency and its method(s) should be advised by particular aspect(s) the IoC container injects an “aspect – aware” bean proxy instead of the bean itself. Method invocations are performed against the proxy bean instance, transparently to the user, in order for aspect logic to be executed before and/or after delegating the call to the actual “proxy–ed” bean.

Furthermore Spring AOP framework uses either JDK dynamic proxies or CGLIB to create the proxy for a given target object. The first one can create proxies only for the interfaces whilst the second is able to proxy concrete classes but with certain limitations. In particular, as stated in Spring reference documentation,
“If the target object to be proxied implements at least one interface then a JDK dynamic proxy will be used. All of the interfaces implemented by the target type will be proxied. If the target object does not implement any interfaces then a CGLIB proxy will be created.”
To summarize, when working with Spring AOP framework you should have two important things in mind :

  1. If your “proxy–ed” bean implements at least one interface, the proxy bean can ONLY be casted to that interface(s). If you try to cast it to the “proxy–ed” bean class, then you should expect a ClassCastException to be thrown at runtime. NeverthelessSpring AOP framework provides the option to force CGLIB proxying but with the aforementioned limitations (please refer to the relevant chapter of Spring reference documentation)
  2. Aspects do not apply to intra–operation calls. Meaning that there is no way for the proxy to intercept the calling of a method originated from another method of the same “proxy–ed” bean
Our recommendation of overcoming the above issues is to use AspectJ weaving. In other words to inject aspect logic directly to the target class and remove the necessity to have all methods being proxied. There are three ways to inject instructions implied by AspectJaspects :
  1. compile time weaving – compile either target source or aspect classes via theAspectJ compiler
  2. post compile weaving – inject aspect instructions to already compiled classes
  3. load time weaving – inject aspect instructions to the byte code during class loading
It's possible to use any of the approaches mentioned above. In this tutorial we will present how to use AspectJ compile time weaving with Spring and Maven. We are going to implement a minimal “greeting” Spring service and a relevant “greeting” AspectJ aspect.Spring service method calls will be intercepted by the AspectJ aspect. The AspectJ aspect will enrich Spring service “greeting” message with its own “greeting” message. The “greeting” message of the AspectJ aspect will be injected from the Spring container, just to show how you can inject Spring dependences to AspectJ aspects.
Spring users who have already implemented aspects for their bean services can switch toAspectJ transparently, meaning that no special code needs to be written since Spring AOPframework uses a subset of AspectJ pointcut expression language, and @AspectJ Springaspects are fully eligible for AspectJ weaving.
Our preferred development environment is Eclipse, so as a prerequisite you must haveEclipse with Maven support installed. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. Nevertheless you will need the following components :
  1. Eclipse from here
  2. Maven Plugin for Eclipse from here
We will be using Eclipse Galileo, „m2eclipse“ Maven Integration for Eclipse Plugin version 0.10.0, Spring version 3.0.1, aspectjrt version 1.6.7 and aspectj-maven-plugin version 1.3 for this tutorial.
Lets begin,
  1. Create a new Maven project, go to File → Project → Maven → Maven Project
  2. In the „Select project name and location“ page of the wizard, make sure that „Create a simple project (skip archetype selection)“ option is unchecked, hit „Next“ to continue with default values
  3. In the „Select an Archetype“ page of the wizard, select „Nexus Indexer“ at the „Catalog“ drop down list and after the archetypes selection area is refreshed, select the „webapp-jee5“ archetype from „org.codehaus.mojo.archetypes“ to use. You can use the „filter“ text box to narrow search results. Hit „Next“ to continue
  4. In the „Enter an artifact id“ page of the wizard, you can define the name and main package of your project. We will set the „Group Id“ variable to „com.javacodegeeks“ and the „Artifact Id“ variable to „aspectjspring“. The aforementioned selections compose the main project package as „com.javacodegeeks.aspectjspring “ and the project name as „aspectjspring“. Hit „Finish“ to exit the wizard and to create your project

Let's recap a few things about the Maven Web project structure
  1. /src/main/java folder contains source files for the dynamic content of the application
  2. /src/test/java folder contains all source files for unit tests
  3. /src/main/webapp folder contains essential files for creating a valid web application, e.g. „web.xml“
  4. /target folder contains the compiled and packaged deliverables
  5. The „pom.xml“ is the project object model (POM) file. The single file that contains all project related configuration.
In order to properly use Spring at runtime, we must provide all necessary libraries to the web application. Open the graphical editor of your „pom.xml“ and perform the following changes :
  1. Locate the „Properties“ section at the „Overview“ page of the POM editor and perform the following changes :
    • Create a new property with name org.springframework.version and value 3.0.1.RELEASE
      • Create a new property with name maven.compiler.source and value according to the version of your Java runtime environment, we will use1.6
        • Create a new property with name maven.compiler.target and value according to the version of your Java runtime environment, we will use1.6
        1. Navigate to the „Dependencies“ page of the POM editor and create the following dependencies (you should fill the „GroupId“, „Artifact Id“ and „Version“ fields of the „Dependency Details“ section at that page) :
          • Group Id : org.springframework Artifact Id : spring-web Version :${org.springframework.version}
            • Group Id : org.aspectj Artifact Id : aspectjrt Version : 1.6.7
            1. Navigate to the “Plugins” page of the POM editor and create the following plugin (you should fill the „GroupId“, „Artifact Id“ and „Version“ fields of the „Plugin Details“ section at that page) :
              • Group Id : org.codehaus.mojo Artifact Id : aspectj-maven-pluginVersion : 1.3
              1. At the “Plugins” page of the POM editor, select the newly created plugin (from the “Plugins” section), and bind it to the compile execution goal. To do so, locate the “Execution” section and create a new execution. At the “Execution Details” section create a new goal and name it “compile”
              2. The newly created plugin needs one final configuration change. We must define what version of Java runtime environment we are using in order for the AspectJ compiler to properly weave aspect classes. We need to edit the “pom.xml” file to perform the change. Select the “pom.xml” page of the POM editor, locate the newly created plugin and alter it as follows :
              <plugin>
              <groupId>org.codehaus.mojo</groupId>
              <artifactId>aspectj-maven-plugin</artifactId>
              <version>1.3</version>
              <configuration>
              <source>${maven.compiler.source}</source>
              <target>${maven.compiler.target}</target>
              </configuration>
              <executions>
              <execution>
              <goals>
              <goal>compile</goal>
              </goals>
              </execution>
              </executions>
              </plugin>
              6. Finally change the “maven-compiler-plugin” as shown below :
              <plugin>
              <groupId>org.apache.maven.plugins</groupId>
              <artifactId>maven-compiler-plugin</artifactId>
              <version>2.0.2</version>
              <configuration>
              <source>${maven.compiler.source}</source>
              <target>${maven.compiler.target}</target>
              </configuration>
              </plugin>

              As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated.
              The next step is to provide hooks for the web application so as to load the Spring context upon startup.
              Locate the „web.xml“ file under /src/main/webapp/WEB-INF and add the following :
              For loading the Spring context upon startup,

              <listener>
              <listener-class>
              org.springframework.web.context.ContextLoaderListener
              </listener-class>
              </listener>
               
               

              Now lets create the applicationContext.xml file that will drive Spring container. Create the file under /src/main/webapp/WEB-INF directory. An example „applicationContext.xml“ is presented below

              <beans xmlns="http://www.springframework.org/schema/beans"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
              xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
              xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
              xmlns:task="http://www.springframework.org/schema/task"
              xsi:schemaLocation="
              http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
              http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
              http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
              http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">

              <context:component-scan base-package="com.javacodegeeks.aspectjspring" />

              <bean class="com.javacodegeeks.aspectjspring.aspects.GreetingAspect" factory-method="aspectOf">
              <property name="message" value="Hello from Greeting Aspect"/>
              </bean>

              </beans>

              Things to notice here :


              1. Change the base-package attribute of the context:component-scan element to whatever is the base package of your project so as to be scanned for Springcomponents
              2. We have to define our aspects in “applicationContext.xml” only if we want to inject dependences to them
              3. AspectJ denotes the term of “aspect association”. It defines how to manage aspect state. The following state associations are supported:

                • Per JVM – one shared aspect instance is constructed and used (default)
                • Per object – aspect has its own state per every advised object
                • Per control flow – aspect has its own state per particular control flow
                  All AspectJ aspect classes have “hasAspect()” and “aspectOf()” static methods. These methods are implicitly generated by AspectJcompiler/load time weaver. So, for the default aspect state there is a single aspect instance that can be retrieved using the “aspectOf()” method

              Lets create now the “greeting” Spring service and the relevant “greeting” AspectJ aspect. Create a sub – package named “services” under your main package and place the “GreetingService” class there. An example “greeting” service is shown below :

              package com.javacodegeeks.aspectjspring.services;

              import org.springframework.stereotype.Service;

              @Service("greetingService")
              public class GreetingService {

              public String sayHello() {
              return "Hello from Greeting Service";
              }

              }
               

              Create a sub – package named “aspects” under your main package and place the “GreetingAspect” class there. An example “greeting” aspect is shown below :

              package com.javacodegeeks.aspectjspring.aspects;

              import org.aspectj.lang.ProceedingJoinPoint;
              import org.aspectj.lang.annotation.Around;
              import org.aspectj.lang.annotation.Aspect;

              @Aspect
              public class GreetingAspect {

              private String message;

              public void setMessage(String message) {
              this.message = message;
              }

              @Around("execution(* com.javacodegeeks.aspectjspring.services.GreetingService.*(..))")
              public Object advice(ProceedingJoinPoint pjp) throws Throwable {
              String serviceGreeting = (String) pjp.proceed();
              return message + " and " + serviceGreeting;
              }

              }

              Finally locate the main Web page of your project, “index.jsp”, under /src/main/webapp folder and alter it as follows :

              <%@ page language="java" import="org.springframework.web.context.WebApplicationContext, org.springframework.web.context.support.WebApplicationContextUtils, com.javacodegeeks.aspectjspring.services.GreetingService"%>
              <%@page contentType="text/html" pageEncoding="UTF-8"%>
              <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
              "http://www.w3.org/TR/html4/loose.dtd">

              <%
              WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
              GreetingService greetingService = (GreetingService) webApplicationContext.getBean("greetingService");
              %>
              <html>
              <head>
              <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
              <title>JSP Page</title>
              </head>
              <body>
              <h1>Test service invoked and greets you by saying : <%=greetingService.sayHello()%></h1>
              </body>
              </html>

              Things to notice here :


              1. Upon page load, we retrieve the Spring Web application context, and lookup our “greeting” service. All we have to do is to invoke the “sayHello()” method to see the combined greeting message from our aspect and the service

              To build the application right click on your project → Run As → Maven package
              To deploy the web application just copy the „.war“ file from the „target“ directory to Apache – Tomcat “webapps” folder
              To lunch the application point your browser to the following address
              http://localhost:8080/{application_name}/
              If all went well you should see your main web page displaying the following :
              “Test service invoked and greets you by saying : Hello from Greeting Aspect and Hello from Greeting Service”
              You can download the project from here
              Hope you liked it
              Justin

              24.10.10

              Don’t Install Spring Roo at Global Directory without Writing Permission (Linux)

              Reason:

                1 #!/bin/sh
              2
              3 PRG="$0"
              4
              5 while [ -h "$PRG" ]; do
              6 ls=`ls -ld "$PRG"`
              7 link=`expr "$ls" : '.*-> \(.*\)$'`
              8 if expr "$link" : '/.*' > /dev/null; then
              9 PRG="$link"
              10 else
              11 PRG=`dirname "$PRG"`/"$link"
              12 fi
              13 done
              14 ROO_HOME=`dirname "$PRG"`
              15
              16 # Absolute path
              17 ROO_HOME=`cd "$ROO_HOME/.." ; pwd`
               35 ROO_OSGI_FRAMEWORK_STORAGE="$ROO_HOME/cache"
              36 # echo "ROO_OSGI_FRAMEWORK_STORAGE: $ROO_OSGI_FRAMEWORK_STORAGE"
              37
              38 ROO_AUTO_DEPLOY_DIRECTORY="$ROO_HOME/bundle"
              39 # echo "ROO_AUTO_DEPLOY_DIRECTORY: $ROO_AUTO_DEPLOY_DIRECTORY"
              40
              41 ROO_CONFIG_FILE_PROPERTIES="$ROO_HOME/conf/config.properties"
              42 # echo "ROO_CONFIG_FILE_PROPERTIES: $ROO_CONFIG_FILE_PROPERTIES"

              22.10.10

              Creating Application using Spring Roo and Deploying on Google App Engine

              http://java.dzone.com/articles/creating-application-using

              Spring Roo is an Rapid Application Development tool which helps you in rapidly building spring based enterprise applications in the Java programming language.  Google App Engine is a Cloud Computing Technology which lets you run your application on Google's infrastructure. Using Spring Roo, you can develop applications which can be deployed on Google App Engine. In this tutorial, we will develop a simple application which can run on Google App Engine.

              Roo configures and manages your application using the Roo Shell. Roo Shell can be launched as a stand-alone, command-line tool, or as a view pane in the SpringSource Tool Suite IDE.

              Prerequisite
              Before we can start using Roo shell, we need to download and install all pre-requites.

              1. Download and install SpringSource Tool Suite 2.3.3. M2. Spring Roo 1.1.0.M2 comes bundled with STS. While installing STS, installer asks for the location where STS should be installed. In that directory, it will created a folder with name "roo-%release_number%" which will contain roo stuff. Add %spring_roo%/roo-1.1.0.M2/bin in your path so that when you can fire roo commands from command line.
              2. Start STS and go to the Dashboard (Help->Dashboard)
              3. Click on the Extensions tab
              4. Install the "Google Plugin for Eclipse" and the "DataNucleus Plugin".
              5. Restart STS when prompted.


              After installing all the above we can start building application.

              ConferenceRegistration.Roo Application
              Conference Registration is a simple application where speaker can register themselves and create a session they want to talk about. So, we will be having two entities Speaker and Presentation. Follow the instructions to create the application:

                ConferenceRegistration.Roo Application
                Conference Registration is a simple application where speaker can register themselves and create a session they want to talk about. So, we will be having two entities Speaker and Presentation. Follow the instructions to create the application:

                1. Open your operating system command-line shell
                2. Create a directory named conference-registration
                3. Go to the conference-registration directory in your command-line shell
                4. Fire roo command. You will see a roo shell as shown below. Hint command gives you the next actions you can take to manage your application.

                5. Type the hint command and press enter.  Roo will tell you that first you need to create a project and for creating a project you should type 'project' and then hit TAB. hint command is very useful as you don't have to cram all the commands it will always give you the next logical steps that you can take at that point.

                6. Roo hint command told us that we have to create the project so type the project command as shown below

                  view source

                  print?

                  1.project --topLevelPackage com.shekhar.conference.registration --java 6

                  This command created a new maven project with top-level package name as com.shekhar.conference.registration and created directories for storing source code and other resource files. In this command, we also specified that we are using Java  version 6.

                7. Once you have created the project, type in the hint command again, roo will tell you that now you have to set up the persistence. Type the following command

                  view source

                  print?

                  1.persistence setup --provider DATANUCLEUS --database GOOGLE_APP_ENGINE --applicationId roo-gae

                  This command set up all the things required for the persistence. It creates persistence.xml, adds all the dependencies required for persistence in pom.xml. We have chosen provider as DATANUCLEUS and database as GOOGLE_APP_ENGINE because we are developing our application for Google App Engine and it uses its own datastore.  applicationId is also required when we deploy our application to Google App Engine. Now our persistence set up is completed.

                8. Type the hint command again, roo will tell you that you have to create entities now. So, we need to create our entities Speaker and Presentation. To create Speaker entity, we will type the following commands

                  view source

                  print?

                  1.entity --class ~.domain.Speaker --testAutomatically

                  2.field string --fieldName fullName --notNull

                  3.field string --fieldName email --notNull --regexp ^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$

                  4.field string --fieldName city

                  5.field date --fieldName birthDate --type java.util.Date --notNull

                  6.field string --fieldName bio

                  The above six lines created an entity named Session with different fields. In this we have used notNull constraint, email regex validation, date field. Spring Roo on app engine does not support enum and references yet which means that you can't define one-one or one-to-many relationships between entities yet. These capabilities are supported on Spring MVC applications but Spring MVC applications can't be deployed on app engine as if now. Spring Roo jira has these issues. They will be fixed in future releases(Hope So :) ).

                9. Next create the second entity of our application Presentation. To create Presentation entity type the following commands on roo shell

                  view source

                  print?

                  1.entity --class ~.domain.Presentation --testAutomatically

                  2.field string --fieldName title --notNull

                  3.field string --fieldName description --notNull

                  4.field string --fieldName speaker --notNull

                  The above four lines created a JPA entity called Presentation, located in the domain sub-package, and added three fields -- title,description and speaker. As you can see, speaker is added as a String (just enter the full name). Spring Roo on Google App Engine still does not support references.

                10. Now that we have created our entities, we have to create the face of our application i.e. User Interface. Currently, only GWT created UI runs on app engine. So, we will create GWT user interface. To do that type

                  view source

                  print?

                  1.gwt setup

                  This command will add the GWT controller as well as all the UI required stuff. This command may take couple of minutes if you don't if you don't have those dependencies in your maven repository.

                11. Next you can configure the log4j to Debug level using the following command

                  view source

                  print?

                  1.logging setup --level DEBUG

                12. Quit the roo shell
                13. You can easily run your application locally if you have maven installed on your system, simply type "mvn gwt:run" at your command line shell while you are in the same directory in which you created the project. This will launch the GWT development mode and you can test your application. Please note that applications does not run in Google Chrome browser when you run from your development environment. So, better run it in firefox.
                14. To deploy your application to Google App Engine just type

                  view source

                  print?

                  1.mvn gwt:compile gae:deploy

                  It will ask you app engine credentials(emailid and password).


                I hope this tutorial will help you in building applications which can be deployed on Google App Engine using Spring Roo. You can test the application @ http://roo-gae.appspot.com/

              21.10.10

              Playing with Spring-Roo

              Actually, I like this type of things. Editing XML configuration files for Spring or Hibernate does not really make sense to me, and most of time, just bothers me. And I really like command line things, although I hate Windows DOS prompt style command lines.

              It is good for me to come with such a simple get-started page:

              http://www.springsource.org/roo/start

              Specifically saying, it is very good to finish my first trial by just looking at the following lines of things:

              mkdir hello
              cd hello
              roo
              roo> hint
              roo> project --topLevelPackage com.foo
              roo> persistence setup --provider HIBERNATE --database HYPERSONIC_IN_MEMORY
              roo> entity --class ~.Timer --testAutomatically
              roo> field string --fieldName message --notNull
              roo> hint controllers
              roo> controller all --package ~.web
              roo> selenium test --controller ~.web.TimerController
              roo> gwt setup
              roo> perform tests
              roo> quit
               
               

              See what the narrator says here:


              Wow! You've now got a webapp complete with JUnit tests, Selenium tests, a MVC front-end, a Google Web Toolkit frontend. Just use “mvn gwt:run” to play with the GWT client, or use “mvn tomcat:run” to start the Tomcat MVC front-end.


              Yes, that is it! Although you might thing it is just a toy program, but it is the base for a real software, and I can build my things based on it.


              And it is also good to have another simple blog page in Chinese to share me such knowledge:


              http://herowzz.javaeye.com/blog/443059

              14.9.10

              Three Approaches to Define a Bean in Spring Context XML

              • Constructor
              • Static factory method (Simple Factory Method)
              • An instance’s factory method (Factory Method)

              Constructor

              <bean id=”exampleBean” class=”examples.ExampleBean” />

              <bean id=”anotherExample” class=”examples.ExampleBeanTwo” />

              Static Factory Method

              <bean id=”exampleBean” class=”examples.ExampleBean2” factory-method=”createInstance” />

              An Instance’s Factory Method

              <bean id=”exampleBean” factory-bean=”myFactoryBean” factory-method=”createInstance” />