Thursday, December 10, 2009

Develop simple JAX-WS web service using Metro

After working on JAX-RPC web services, it is time to go for much acclaimed web services technology JAX-WS. People says it is an extension of JAX-RPC, some says it’s a replacement of JAX-RPC.

Let me brief you about some difference between JAX-RPC and JAX-WS before we jump to jax-ws service.

  • JAX-WS maps to Java 5. So features of Java 5 are supported like annotations, generics, etc.
  • Support SOAP 1.1 and 1.2
  • support WS-I basic profile 1.1 (new version)
  • JAX-RPC has it’s own data type mapping model and covering 90% of XML schemas. However I have experienced interoperability issue while using JAX-RPC. JAX-WS uses JAXB mapping model which covers all XML Schemas with less interoperability issues.

Detailed features list/comparison is available on http://www.ibm.com/developerworks/webservices/library/ws-tip-jaxwsrpc.html (worth reading!!!!)

Discussing my own experience, Recently I have been involved in assignment where we had to replace existing AXIS services with JAX-WS services. When we started, we were not sure about success because our applications were first one who stared this remediation. I remember we haven’t had any major hitch (like Interoperability) in remediation task. These services have different types of consumers like .NET application, J2EE application, Workflow Tool. Moreover many of these services were using standard java types like HashTable, Map (either as a input parameter or return type) and luckily we did not face any issue during remediation. All these consumers are able to access new service without any issue. :).

Now let’s start with JAX-WS web services. We all know that services can be developed either using Top-down approach(i.e. WSDL-web service) or bottom up (i.e. web service – WSDL) approach . Metro is supporting both approaches. It provides command line/ant tasks utilities (same as wsdl2java and java2wsdl). If you are using NetBeans IDE then it will generate artifacts in few clicks. You will also find eclipse plugin for the same.

Let me explain steps to develop simple JAX-WS service using Metro RI. Here I am talking about top-down approach (which is recommended in web service development).

1) Design your wsdl first. You can use either doc/literal or rpc/encoded. Now a days most of the applications are using doc/literal style of web service. I have also used same style.

   1: <?xml version="1.0" encoding="UTF-8" standalone="no"?>
   2: <wsdl:definitions xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
3: xmlns:tns="http://hello.jaxws.webservice.com" xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
4: xmlns:xsd="http://www.w3.org/2001/XMLSchema" name="HelloService"
5: targetNamespace="http://hello.jaxws.webservice.com">
6: <wsdl:types>
7: <xsd:schema targetNamespace="http://hello.jaxws.webservice.com">
8: <xsd:element name="HelloJAXWSServiceRequest">
9: <xsd:complexType>
10: <xsd:sequence>
11: <xsd:element name="in" type="xsd:string" />
12: </xsd:sequence>
13: </xsd:complexType>
14: </xsd:element>
15: <xsd:element name="HelloJAXWSServiceResponse">
16: <xsd:complexType>
17: <xsd:sequence>
18: <xsd:element name="out" type="xsd:string" />
19: </xsd:sequence>
20: </xsd:complexType>
21: </xsd:element>
22: </xsd:schema>
23: </wsdl:types>
24: <wsdl:message name="HelloJAXWSServiceRequest">
25: <wsdl:part element="tns:HelloJAXWSServiceRequest" name="parameters" />
26: </wsdl:message>
27: <wsdl:message name="HelloJAXWSServiceResponse">
28: <wsdl:part element="tns:HelloJAXWSServiceResponse" name="parameters" />
29: </wsdl:message>
30: <wsdl:portType name="HelloService">
31: <wsdl:operation name="HelloJAXWSService">
32: <wsdl:input message="tns:HelloJAXWSServiceRequest" />
33: <wsdl:output message="tns:HelloJAXWSServiceResponse" />
34: </wsdl:operation>
35: </wsdl:portType>
36: <wsdl:binding name="HelloServiceSOAP" type="tns:HelloService">
37: <soap:binding style="document"
38: transport="http://schemas.xmlsoap.org/soap/http" />
39: <wsdl:operation name="HelloJAXWSService">
40: <soap:operation soapAction="http://www.example.org/HelloService/NewOperation" />
44: <wsdl:output>
  45:                 <soap:body use="literal" />
  46:             </wsdl:output>
  47:         </wsdl:operation>
  48:     </wsdl:binding>
  49:     <wsdl:service name="HelloService">
  50:         <wsdl:port binding="tns:HelloServiceSOAP" name="HelloServiceSOAP">
  51:             <soap:address location="http://localhost:8080/helloservice/HelloWebService" />
  52:         </wsdl:port>
  53:     </wsdl:service>
  54: </wsdl:definitions>

2) Add ws-import task in your ant script. Make sure you have jax-ws libraries in classpath before executing it. (note: to execute this task from build script, just add jaxws-tools.jar in Ant classpath)


   1: <taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport">
   2:      <classpath refid="jaxws.classpath"/>
   3:  </taskdef>

3) add below target to generate jax-ws artifacts using ws-import task.

   1: <target name="wsgeneration" description="generating jax-ws artifacts">
   2:         <wsimport wsdl="${basedir}/WebContent/WEB-INF/wsdl/HelloService.wsdl"
   3:             destdir="${build.home}" sourcedestdir="${root}/src" verbose="true"
   4:             keep="true">
   5:         </wsimport>
   6: </target>

I have shown basic attributes here for generating artifacts. “wsdl” contains wsdl location (you can keep it anywhere). “dest-dir” should be directory in which generated artifact classes will be placed. “sourcedestdir” contains generated source files.

Successful execution of buid script will generate below set of artifacts.(Note: Below list may vary depending upon your schema definition)

HelloJAXWSServiceRequest.java (request object as defined in wsdl)
HelloJAXWSServiceResponse.java(response object as defined in wsdl
HelloService_Service.java
HelloService.java (SEI – service endpoint interface)
ObjectFactory.java (annotated source files)
package-info.java

4) Now create an implementation class say HelloServiceImpl which implements SEI (i.e. HelloService here)

  1: /**
   2:  * 
   3:  */
   4: package com.webservice.jaxws.hello;
   5:  
   6: /**   
   7:  * @author chintz
   8:  *
   9:  */
  10: public class HelloServiceImpl implements HelloService {
  13:     @Override
  14:     public HelloJAXWSServiceResponse helloJAXWSService(
  15:             HelloJAXWSServiceRequest parameters) {
  17:         //get web service in parameters from request
  18:         String inParam = parameters.getIn();
  20:         //do some processing
  21:         String response = "Hello" + inParam;
  23:         //set response in HelloJAXWSServiceResponse object
  24:         HelloJAXWSServiceResponse wsRes = new HelloJAXWSServiceResponse();
  25:         wsRes.setOut(response);
  27:         //return response
  28:         return wsRes;
  29:     }
  31: }

5) Add JAX-WS listener and servlet entries in web.xml. This listener and servlet is useful in initializing JAX-WS runtime. Listener is same like Spring’s ServletContextLoaderListener whose job is to initialize Spring framework.



   1: <listener>
   2:     <listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
   3: </listener>
   4: <servlet>
   5:     <description>JAX-WS endpoint</description>
   6:     <display-name>JAXWS servlet</display-name>
   7:     <servlet-name>helloservice</servlet-name>
   8:     <servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
   9:     <load-on-startup>1</load-on-startup>
  10: </servlet>
  11: <servlet-mapping>
  12:     <servlet-name>helloservice</servlet-name>
  13:     <url-pattern>/helloservice</url-pattern>
  14: </servlet-mapping>

6) Create sun-jaxws.xml which contains endpoint implementation details.

   1: <endpoints xmlns='http://java.sun.com/xml/ns/jax-ws/ri/runtime' version='2.0'>
   2:     <endpoint
   3:         name='helloService'
   4:         implementation='com.webservice.jaxws.hello.HelloServiceImpl'
   5:         url-pattern='/helloservice'/>
   6: </endpoints>

So whenever any request comes with defined url-pattern (in our case “helloservice”) it will look for service implementation details from sun-jaxws.xml and execute corresponding service method.

Now bundle everything in WAR file and deploy it. If you see message like “Initialized WSServlet” and “JAX-WS framework ready” (on server console) during deployment it means that you are all set.
Verify your service deployment by accessing: (http://localhost:8080/helloservice/HelloWebService) or wsdl (http://localhost:8080/helloservice/HelloWebService?wsdl)

So your simple Hello JAX-WS service ready. Now test it using client application. To start with, test it using SoapUI tool.

Hope this article will help you in developing JAX-WS service.

Thursday, June 25, 2009

Introduction to Spring Security

Recently I have given presentation on Spring Security framework. Before I talk about Spring Security, I will brief you about what is all about security framework and why it is really important?

You must have heard word “Security” many times. In your day-to-day life as well as while writing a simple computer program. Dictionary meaning of Security is “degree of protection against danger, lost and criminals”. Well “Criminals” in computer world is none other than “Hacker”. :) I hope you are aware of what does “Hacker” mean? :)

So let’s see how Security is important for an enterprise and it’s software applications. In today’s world security has become ever-moving target for an enterprise. All enterprise wants their system to be as secure as possible in its own right. In IT realm security is categorized as “Layers of Security”. i.e.each layer should be secured enough. There are 4 Layers of Security which are listed below.

Transport Layer Security – this is generally achieved using SSL protocol. provides security and data integrity over network such as internet, intranet, VPN.

Network Security – this is achieved using IPSec

Data/Information Security – this can be achieved using message encryption techniques like using X.509 Certificate.

Application Security – this is generally achieved using Security frameworks like Spring Security, Java EE Security.

I believe you must have learnt “layers of security” during your Engineering/Graduation (probably as a part of “Computer Networking” subject) :). No worries if you have forgotten, I will help you to give basic understanding..if you still not understand. you can search on google!!!!! :)

Now let’s get back to our main topic…

Here I will talk about Application Security which is taken care by security framework like Spring Security. Security framework generally take care of Authentication, Authorization (i.e. Access Control mechanism), Encryption, Session management (i.e. preventing men-in-middle attack, session hijacking) , Auditing and logging.

Now let’s talk about what is Spring Security (aka Acegi Security)? Earlier it was known as Acegi Security framework which is merged with Spring and now known as Spring Security framework.

Spring Security provides comprehensive services (i.e. Authentication, Authorization, Encryption, etc) for J2EE based enterprise s/w application.

Let me talk about why this framework is gaining popularity.

  • Lack of depth of security in Servlet and EJB Specifications. These specifications support primary authentication and authorization services like BASIC, FORM and Digest authentication and method level authorization services.
  • Again they are not portable at EAR and WAR level so if you switch to other Application Server environment, you may have to reconfigure these settings.
  • Since Spring Security is built upon Core Spring, you can leverage core spring features like Dependency Injection (DI), AOP (Aspect Oriented Programming), PropertyConfigurator, etc.
  • Apart from that Spring Security provides dozen of useful, entirely customizable security features. I will discuss few of them here.

Now let’s talk about Spring Authentication and Authorization one-by-one.

Authentication i.e. “Check if the principal (i.e. users or system) is who he/she says he/she is”.

Sprint Security provides easy integration with different types of authentication mechanism. I have listed few of them below. You can get full list in Spring Security docs.

  • HTTP BASIC authentication
  • HTTP Digest authentication
  • HTTP Form based authentication
  • HTTP X.509 client certificate exchange
  • LDAP
  • OpenID authentication (OpenID is also gaining popularity and major companies liek Google, Microsoft, Sun, Oracle, Yahoo support OpenID authentication) you can get more details on http://en.wikipedia.org/wiki/OpenID )
  • Computer Associates Siteminder
  • Central Authentication Service ( known as CAS package, a popular Single Sign-On (SSO) system)
  • “Remember-me” authentication
  • Anonymous, Run-as and JAAS (Java Authentication and Authorization Service)
  • Also support for container( i.e. Tomcat, JBoss, Jetty) based authentication mechanism

Apart from above listed support, framework also provides integration with Grails, Mule ESB, Tapestry and last but not the least your own Authentication Mechanism. Spring also supports Channel Security (through HTTPS) with JCaptcha (a java based s/w application to ensure that response is not generated by computer).

i have talked much about authentication support provided by framework. Now let’s discuss about authorization support provided by framework.

Authorization i.e. “how an application grants access to content and functions to some principals and not others

Advanced authorization capabilities is one of the reason for gaining popularity of this framework. Irrespective of your authentication mechanism, you can use framework’s Authorization services in your application.

So if we go by the definition of authorization, we want service layers methods and objects to be accessed by specific users based on roles defined either in the property file, database,LDAP or some other repositories. Spring Security provides three types of interceptors to achieve this functionality.

  • AOP Alliance (MethodInvocation) Security Interceptor
  • AspectJ (JoinPoint) Security Interceptor
  • FilterInvocation Security Interceptor

Don’t think how these interceptor works, i will discuss it in next article. For your knowledge, Interceptors are used to intercept request and do some processing on it, like authentication, authorization, logging, auditing, etc.

Note: All authentication and authorization is provided by Spring Security framework is based on various Filters. I will discuss this in detail in next article.

I hope you have now basic understanding of Spring Security and it’s features. In next article i will show you example how simple web application can be easily configured with Spring Security. It is more configuration based and less coding..i am sure you must be happy :)

I would suggest you to also explore other security frameworks in J2EE arena, like Java EE Security, OWASP(Open Web Application Security Project) Enterprise Security API, BoncyCastle, jGuard.

Don’t forget to visit my next article which will be continuation of this!!!! Have a nice day :)

Tuesday, May 19, 2009

Hibernate session.get () Vs session.load ()

Subscribe in a reader


In my recent assignment, we had a requirement to fetch a single row from DB (i.e. entity) using Hibernate framework. So Session.get(Class clazz, Serializable id) straightaway came into my mind. However

there is one more function named Session.load(Class theClass, Serializable id) to achieve same functionality.


Since both functions are part of Session interface, there has to be some difference between each of them. Let's see their usage and differences.



Sesion.get( Class theClass, Serializable id) throws HibernateException

It returns persistent instance of the given entity class with the given identifier. Incase of non-existence it will return null.


So to get an entity from the underlying persistence store, all you have to do is call Hibernate Session’s get method and provide two arguments: Java class associated with the entity that you are retrieving which in our case would be User.class and actual primary key associated with the record. i.e.


session.beginTransaction();
User user = (User)session.get(User.class, new Long(1));
System.out.println(user.getPassword());
session.getTransaction().commit();

In above code, I have simply retrieved an instance of User class using get () and then printing “password” property before transaction commit.


Now same code, instead of get () I will use load () as below. Before that let me explain definition of session.load ()


public Object load(Class theClass, Serializable id) throws HibernateException returns persistent instance or proxy of a class with the given identifier. We can not use this method to determine if an instance is exists. In case of non-existence of the instance it will throw an exception.

session.beginTransaction();
User user = (User)session.load(User.class, new Long(1));
System.out.println(user.getPassword());
session.getTransaction().commit();


I have shown code snippet for both methods, now let’s concentrate on real part and that is comparison between these two methods.

Well if you were to compare the load and the get method of Hibernate Session, it looked pretty similar, and you’d be correct. However there are subtle and importance differences.


First of all, the Get method hits Database as soon as it is called. So this method will always trigger a DB hit. While load method will hit the database when particular field is accessed (i.e. user.getPassword ()) so if you use load method to retrieve an entity, but you never actually access any field of the entity, it never hits the database. I think this is pretty good.



Well, actually, as per above description, load method might sound good, but it triggers more problems then it solvesL. Let’s understand WHY?


When you initialize java bean (i.e. entity) from the load method, you can only access the properties of the java bean, for the first time, with in transactional context in which it was initialized.


When you try to access various properties outside of the transactional context that has been already committed, you will get LazyInitializationException, as hibernate no longer has valid transactional context to use and hit the database.


So below code will fail and throw LazyInitializationException – Could not initialize proxy – no session


session.beginTransaction();
User user=(User)session.load(User.class, new Long(1));
session.getTransaction().commit();
System.out.println(user.getPassword());

So, big thing to understand from the load method is, you can’t really use loaded JavaBean after the transaction is committed, whereas, you can use get method, because all the properties of the JavaBean has been initialized right away

Now let’s us talk about one more difference. What happens when you provide a primary key that doesn’t exists in the database? Well, with the get method, it will simply return null object, which is no big deal, I can simply put a null check in my DAO class method.


But with the load method, again it will not create any problem when you an invalid primary key. Does that mean, it will return a null object or what? Well, the answer is simply NO. You will run into problem when you try to access a property of that instance.

So after comparing load and get methods, you will ask when to use load ()? And when to use get ()? Let’s see….

Use get (

  • If you ever want to use JavaBean properties even after transaction has been committed. And quite frankly, that tends to be most of the time. For example, if you load a User instance in a Servlet, and you want to pass that instance to a Java Server Page for display purposes, you'd need to use the get method, otherwise, you'd have a LazyInitializationException in your JSP
  • If you are not sure that entity with the given primary key is exists or not

Use load ()

  • If your goal is transactional and you want to access JavaBean properties with in the specified transaction
  • If you want to ensure that JavaBean is sync with the database, you will use load method. Because it will ensure that fields are loaded in from the database and not from the JVM on which you are running
  • If you are absolutely sure that the entity you are searching is already present in database.

I hope above explanation will help you to understand differences between both functions and their actual usage.

With good understanding of these two functions will surely help you in avoiding LazyInitializationException

Subscribe in Reader