Showing posts with label GlassFish 4. Show all posts
Showing posts with label GlassFish 4. Show all posts

Monday, September 23, 2013

Using Arquillian with JUnit and Glassfish for Integration Testing

We are all familiar with Junit as a unit and integration testing framework. This article talks about configuration of JUnit with Arquillian for Integration testing on Glassfish 4.
Arquillian (http://arquillian.org/) provides a component model for integration tests, which includes dependency injection and container life cycle management. Arquillian lets you ditch the mocks and write real tests. That's because Arquillian brings your test to the runtime, giving you access to container resources, meaningful feedback and insight about how the code really works.

Following article will present a test project, where we have a service endpoint resource class (RESTResource.java) which is a service endpoint for a RESTful webservice. The RESTful request comes to this endpoint class and it calls the business service (ServiceImpl.java). We using Java EE 7, CDI (context & dependency injection - JSR 299 specification) to inject ServiceImpl in RESTResource. Now we use also have a OraServiceDAO that does a resource lookup (using Java EE @Resource) of Oracle Data source. This OraServiceDAO is also injected into ServiceImpl using CDI. This kind of 
The problem most developers will have while writing integration tests would be, how to simulate CDI and JNDI resource look up as done in OraServiceDAO, while doing integration testing without an actual Glassfish 4 environment running. Arquillian come to our rescue and along with JUnit it provides an embedded Glassfish environment for running integration test cases.

First I would like to introduce our project structure. 

RESTResource is the RESTful web service endpoint that receives the GET request.


ServiceImpl is injected into it using CDI. using Arquillian and JUnit we would write an integration test case that would test this business service namely testService API.

ServiceImpl class

If you see, the Oracle DAO OraServiceDAO is injected into this business service class.


OraServiceDAO  class



This class looks up JNDI resource to get the Data source.

Now if you see the complexity of this simple example, framework like JUnit would not be sufficient alone to test CDI and resource look ups done in this example without external help. Arquillian comes to rescue..!!  

Using Arquillian and JUnit we can simulate the Glassfish environment and run test cases.

First I would introduce with the Maven environment setting defined in pom.xml for running Arquillian, JUnit and embedded Glassfish using Maven.

Following versions of dependencies are being used in pom.xml
<properties>
        <arquillian.version>1.0.0.Final</arquillian.version>
        <jersey.version>2.0</jersey.version>
        <junit.version>4.11</junit.version>
        <glassfish.embedded.all.version>4.0</glassfish.embedded.all.version>
        <arquillian.glassfish.embedded.version>1.0.0.CR4</arquillian.glassfish.embedded.version>
   </properties>

I’m using the arquillian-bom (Bill Of Material) who contains all the versions for the arquillian dependencies.


The Arquillian & Junit dependencies:-


Build profile setting:-

Now the resource files defined above and required for Arquillian to correctly setup the resources

arquillian.xml

<?xml version="1.0" encoding="UTF-8"?>
<arquillian xmlns="http://jboss.org/schema/arquillian"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://jboss.org/schema/arquillian
        http://jboss.org/schema/arquillian/arquillian_1_0.xsd">
    <container qualifier="glassfish-embedded" default="true">
        <configuration>
            <property name="resourcesXml">
              src/test/resources-glassfish-embedded/glassfish-resources.xml
             </property>
        </configuration>
    </container>

</arquillian>

glassfish-resources.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC
    "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN"
    "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>

    <jdbc-resource pool-name="ArquillianEmbeddedOraclePool" jndi-name="jdbc/testresource/ORAlookup"/>
    <jdbc-connection-pool name="ArquillianEmbeddedOraclePool" res-type="javax.sql.DataSource"
        datasource-classname="oracle.jdbc.pool.OracleDataSource" is-isolation-level-guaranteed="false">

  <property name="URL" value="jdbc:oracle:thin:@oraserver.com:1521:ora1"/>
    <property name="User" value="username"/>
    <property name="Password" value="password"/>

    </jdbc-connection-pool>
         

</resources>


Now let us look at the Test class which call its all:-



Line 25 - you have to use @RunWith annotation to specify 
Line 35 - ShrinkWrap api, that assembles it all. Shrinkwrap provides a simple mechanism to assemble archives like JARs, WARs, and EARs with a friendly, fluent API.
Line 47 - Injecting ServiceImpl

This is a JUnit test class that uses Arquillian to create archive that runs on embedded Glassfish env.



The structure of the complete project looks like:-






Finally, you can run maven install or maven test using Eclipse or from command prompt cmd> mvn clean install. You will see in the output logs, that Service and oracle DAO is called.




This example uses Arquillian to startup Glassfish env and run integration testing using JUnit.


Friday, August 30, 2013

Aspect Oriented Programming (AOP) using CDI for Java EE

As defined by wikipedia, aspect-oriented programming (AOP) is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. AOP forms a basis for aspect-oriented software development. (Aspect oriented programming)
Using AOP we break down our program logic into distinct parts called concerns. Aspects enable the modularization of concerns such as transaction management that cut across multiple types and objects. 
Certain terms and terminology commonly used in AOP are:-
  • Aspect: a modularization of a concern that cuts across multiple classes.
  • Join point: a point during the execution of a program
  • Advice: action taken by an aspect at a particular join point.
AOP has been very common in Spring Framework and is also available in Context & Dependency Injection (CDI) for Java EE. 
The benefits of using AOP are:-
  1. modularization of system level coding i.e. logging, transaction, security 
  2. minimal coupling and duplication of code making it easier to add new functionalities.
  3. faster development as developers can focus mainly on the business logic rather than thinking of cross-cutting concerns such as security, transaction, logging etc. The business logic looks clear and does not have logging, security, transactional details.

Some example areas where AOP can be used:-

  1. Logging - We can write aspect around methods so that we can log before and after states of a method without actually putting logging statements in the actual method.
  2. Transaction management - in applications where transaction has to be managed manually, we can write aspects to begin and commit or rollback transactions depending on success or failure of the business method.
  3. Security - we can apply method level security around a method. So we do not have to implement security and role check in every business method. Aspect can be written that will be fired before a method is invoked and incase the user is not authenticated it will return an exception.
  4. Checking and using cached data before data access from database - we can write aspects around a data access method which will access the cache to see if the data is present. Incase the data is present it will return the data from the cache. Otherwise it will make data access call to the database and also add the returned data to the existing cache. Sample application below will use this as an example. 

Sample Application

Since we are developing using CDI for Java EE, I will present a sample implementation of AOP and cross-cutting using Java EE. This application uses Glassfish 4 as the application server and using Java EE.
 In this application I will show how we can write an Aspect around a web service method. This aspect will be fired before and after the web service method and can be used for security validation as well as checking cached data before making a DB call.
 We have a RestFulService service, which handles RESTful calls. Method retrieveRecordByResource handles the @Get RESTful call and retrieves all the parameters that are sent as part of the RESTful service. 
We will create an aspect around this call, which will
  • monitor the variables coming as input to the REST call 
  • response returned as part of the REST call
  • will modify variables before the call reaches retrieveRecordByResource method.
Code for Advice:-

In the code above, we create an advice class and method checkCache, with annotation @AroundInvoke. @AroundInvoke defines an interceptor method that interposes on business methods. 
Line 42, calls the proceed api of InvocationContext. Before this call we see that we have extracted the input parameters that came as input from the REST service call. It also returns returnParam which is the output after the call to our business method retrieveRecordByResource. 
Line 31 to 42, we see that we have extracted input parameters before the call to business method and we can manipulate these variables. We can do logging, security check, transaction management etc. before actually calling the business method. 
Line 44, we have control of the output parameters and we can log or manipulate these parameters. 

Line 17, defines an annotation @CacheResource. We need to define an interface CacheResource for the same.


In simple terms this interface and annotation @CacheResource, link our advice and the business class.
The interceptor is defined in WEB-INF/beans.xml:-

This configuration defines our interceptor. 

Conclusion:-
AOP is a very useful and powerful feature of OO programming. CDI brings AOP and dependency injection (DI). We can integrate AOP with caching using caching frameworks like JCache or EhCache.
CDI is the Java standard for dependency injection and interception (AOP). You can read futher about the same in JSR 299.

Wednesday, August 21, 2013

GlassFish 4 plugin with Eclipse Juno

Java EE 7 & GlassFish 4 are getting hot in popularity. With GlassFish 4 being adopted by many enterprises for their application development and EAI, hence I thought of writing this post of a quick way to introduce GlassFish into yours and your eclipse's life.

The GlassFish Server is a compliant implementation of the Java EE 7 platform. 

The GlassFish Eclipse Plugins
The starting place for Eclipse are the GlassFish Eclipse plugins. They moved into the Oracle Enterprise Pack for Eclipse (OEPE) project a while back and are still there to be installed and configured separately.



Install the Plugin
This works as expected. If you stick to the update site you simply go to Preferences->Install/Update->Available Software Sites and make sure that the above mentioned site is defined and checked. Install the GlassFish Tools and the Java EE 6 and/or Java EE 7 documentation and sources according to your needs. Click next two times, read through the license and check accept. Click Finish to install. The download gets everything in place and you have to finish the installation with a re-start.

I had some of the componenet already installed hence in the below pic you will not see all the components that will be available for download.


Add GlassFish as your server

In the server type, look for Glassfish.  If not there, click ‘Download additional server adapters’.  Look for and click on Glassfish Tools and click Next. Go through prompts to download.  Eclipse will likely need to be restarted. Then go through steps to set up a new server again.



You can also access the Glass fish admin console using URL - http://localhost:4848/