Translate

Monday, 13 January 2014

OAuth Simplified

OAuth 2.0 is an authorization protocol which applications can use for accessing each other data. A more common scenario which you all have seen is to login into a website using your Facebook or Google account. In this article we will understand OAuth 2.0 protocol which is release in Oct 2012. It is much simpler than its previous version 1.0, as 1.0 involve certificate which is removed from 2.0. OAuth protocol will have following participants

  1. Resource Owner
  2. Resource Server
  3. Client Application
  4. Authorization Server
The resource owner can be a user or application which has data that can be share with other application. For example an user on Facebook or Google can be consider as Resource Owner and his profile/account data can be consider as resource.
The Resource Server is the application which stores resource like Facebook and Google can be consider as Resource Server.
The client application is the application which request for accessing resources. Lastly Authorization server is the server for authorizing (credential validation logic) a client application to access resource hosted by Resource Server. Usually Resource servers itself host logic for credential validation but OAuth specification has specified it as a separate component. It’s up to our use case where to implement authorizing logic.

Now we have understanding of OAuth components we will see how OAuth works.
Before a Client application can request a resource access, it needs to register itself with Authorization server. This is one time task in which Authorization Server provides a client ID and client secret. Client will also specify a URI on which Authorization server will redirect when authorization is successful. This credential will recognize client in future communication with authorization server.
Client application needs to provide a link or button asking user to log in using Authorization server like Facebook or Google. Clicking on button will redirect resource owner to Authorization server and owner will get validate by providing credentials. This URI is referred as Authorization Endpoints in OAuth 2.0 specification. An Authorization server will then ask User/resource owner to grant access to client application for accessing resource. Once User accepts it, Authorization server will redirect user to client application URI. This is the same URI client has registered with Authorization server at the time of registration. This URI is reference as Redirect endpoint in OAuth 2.0 specification.
In OAuth 2.0 specification there can be 4 types of Authorization Grant

  1. Authorization Code
  2. Implicit
  3. Resource Owner and password
  4. Client credentials
In Authorization code when user accepts the authorization grant to client application, it will redirect to client application URI along with an Authorization code in response. Client application will then request Access Token URI on Authorization Server with Client ID, Client Secret and Authorization Code as request parameters and will get access token in response. Client application will then use Access Token with further communication. The Access token can be expired after a period and client application will again need to request an access token. Access token URI is referenced as Token endpoint in OAuth specification.

The Implicit Authorization grant is similar to authorization code except instead of returning an Authorization code, Authorization server will return access token itself which can then be used for further communication.

In Resource owner password Authorization grant user provides its Authorization server credentials to client application. For example a user enters Facebook or Google account credentials on client application. Client application would then use username and password for further communicating with Facebook or Google. This type of Authorization grant will be used in highly trusted client application.

The Client credentials authorization code works when client application need to access resource which are not related to any specific resource owner.

For Further details on request and response structure please refer http://tools.ietf.org/html/rfc6749

If you are on Java side then you can use Apache Oltu or Spring security as OAuth provider for your application. Please visit below for more details.



Friday, 27 December 2013

Dive into WSDL


Everybody who is working with web service knows about WSDL document. WSDL stands for web service descriptive language and is used for describing a web service in language & implementation independent way. When I say language independent, means it is an xml document. WSDL document provides a detail description about a web service, about operation supported by web service, input and output parameter of an operation. With number of web service framework available, writing a web service is merely placing some annotations on business java class. Framework like CXF and others application server provides utility to generate a WSDL document using Java code and vice versa. With the use of utility we normally didn’t have to deal with different elements of WSDL document. But knowing about WSDL elements detail will help us to debug our application effectively.

I have created a sample web service project. You can access complete project from Git repository https://github.com/vcjain/webservice.git and can refer to employee.wsdl document.

A WSDL document has below top elements and they include other elements in turn.
  1. Definitions
  2. Types
  3. Message
  4. Port Type
  5. Binding
  6. Service


The <definitions> element is a root element and specifies namespace for different XML schemas.

<definitions name="employee" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
                xmlns:tns="http://cxfsoap.vcjain.com/" xmlns="http://schemas.xmlsoap.org/wsdl/"
                xmlns:xsd="http://www.w3.org/2001/XMLSchema" targetNamespace="http://cxfsoap.vcjain.com/">

The name attribute is merely a name given to a WSDL document. It is not used in any processing and acts as an identifier only. In above example we have used default namespace for WSDL schema hence we can avoid prefix on a wsdl schema element in rest of document. The targetNamespace attribute will identify the namespace for element define in the WSDL document.

The <types> element is used to define any custom data type used in web service. For an example in our web service we have a POJO object Employee which is an input parameter in addEmployee operation. We can define Employee schema in <types> element. We can also import a schema specifying a location. Prefer to define all imports before defining any XML element. Below is how a <types> element declaration looks like in the WSDL document
<types>
          <import namespace=" http://cxfsoap.vcjain.com/"  location="http://cxfsoap.vcjain.com/department.xsd"/>
          <xsd:schema targetNamespace="http://cxfsoap.vcjain.com/">

<!—Defining Employee objectà
               
<xsd:complexType name="employee">
                                <xsd:sequence>
                                                <xsd:element minOccurs="0" name="firstName" type="xsd:string" />
                                                                <xsd:element name="ID" type="xsd:long" />
                                                                <xsd:element minOccurs="0" name="lastName" type="xsd:string" />
                                                                                <xsd:element maxOccurs="unbounded" minOccurs="0" name="subjects"
                                                                                                nillable="true" type="xsd:string" />
                                                                </xsd:sequence>
                                                </xsd:complexType>
                                               


<!—Defining Exceptionà
<xsd:element name="NameMismatchFaultDetails">
                                                                <xsd:complexType>
                                                                                <xsd:sequence>
                                                                                                <xsd:element name="code" type="xsd:int"></xsd:element>
                                                                                                <xsd:element name="message" type="xsd:string"></xsd:element>
                                                                                </xsd:sequence>
                                                                </xsd:complexType>
                                                </xsd:element>
                                </xsd:schema>


                </types>

In above snippet we have defined two Java object Employee and NameMisMatchException which are used in our web service. Other tags are simple XML tag used to define a schema.

The <message> element is used to describe incoming and outgoing messages of the web service. The way a message is define is based on whether we use messaging style as ‘rpc’ or ‘document’. In WSDL document we define multiple messages corresponding to input parameter, out parameter, SOAP headers and faults. A message in itself cannot be identified as input/output/fault. These messages are further referenced in <porttype> element to define their basic type (input/output/fault) and associate them with operations. The name attribute can have any name but it is a good convention to suffix message with request, response and fault to specify as Input, output and Exception message.
                 <message name="addEmpRequest">
                                <part name="employee" type="tns:employee"></part>
                </message>
                <message name="addEmpResponse">
                                <part name="response" type="xsd:string"></part>
                </message>
                <message name="NameMisMatchException">
                                <part name="NameMisMatchException" element="tns:NameMismatchFaultDetails"></part>
                </message>
                <message name="accept_header">
                                <part name="Accept" type="xsd:string"></part>
                </message>

A message can have a multiple parts. You can consider each part as a separate argument. If a method in your web service takes two arguments then we may need to define a message with two parts and each part representing an argument. In Java for calling a method we need to pass method argument in specified order hence in WSDL parts will take precedence in the order in which we define in WSDL document; moreover we can define order of parts (argument) in operation element under <porttype>. When we implement a web service in Java we can have only one return type hence an output message will only have one part. Since a web service can be implemented in any language other than Java, there is a notion of multiple parts in output message too.

The <porttype> element defines an abstract interface of a Web service. It resemble to a Java interface, with operation element resembling to Interface methods.
<portType name="EmpService">
                                <operation name="addEmp">
                                                <input message="tns:addEmpRequest"></input>
                                                <output message="tns:addEmpResponse"></output>
                                                <fault  name="NameMisMatchException" message="tns:NameMisMatchException"></fault>
                                </operation>
                </portType>
The <operation> element defines name of operation and input, output and fault parameters. Each
Operation is composed of at most one input or output element and any number of fault elements. You can add parameterOrder attribute to operation tag to define specific order of input parts.

The <binding> element relates the abstract interface <porttype> element to concrete internet protocols, messaging styles and encoding styles. The <binding> element is composed of two different namespace elements, wsdl specific elements and protocol specific elements.

<binding name="EmpServiceBinding" type="tns:EmpService">
                                <soap:binding transport="http://schemas.xmlsoap.org/soap/http"
                                                style="rpc" />
                                <operation name="addEmp">
                                                <soap:operation style="rpc" />
                                                <input>
                                                                <soap:body use="literal" namespace="http://cxfsoap.vcjain.com/"/>
                                                </input>
                                                <output>
                                                                <soap:body use="literal" namespace="http://cxfsoap.vcjain.com/"/>
                                                </output>
                                                <fault name="NameMisMatchException">
                                                                <soap:fault name="NameMisMatchException" use="literal" namespace="http://cxfsoap.vcjain.com/"/>
                                                </fault>
                                </operation>
                </binding>

Each internet protocol has their own set of elements which describe protocol specific settings. In above snippet we have associate <porttype> with a SOAP protocol. Hence you can see different SOAP protocol specific tag like soap:binding, soap:operation, soap:body in binding element. If you are using HTTP protocol then you may have define http:binding, http:operation, http:urlEncoded etc elements.

The soap:binding element specify the internet protocol used to send soap messages (transport attribute)and default messaging style for operations (style attribute). J2EE web service only supports soap protocol and HTTP protocol for message transfer. The soap:operation element is specific to each operation and can override the default messaging style define in soap:binding element. The element soap:body specify encoding style of input, output and fault parameters (use attribute). It can be set to literal or encoding. If you closely look then you find that operation element of <binding> is directly associated with the operation element of <porttype>. In binding element we are associating each port type operation with its messaging and encoding style and defining a transfer protocol for a web service. There are some other soap specific elements also like soap:header, soap:headerfault etc but these are optional.

The last element is the <service> element which associated an endpoint URI (address) with a web service definition.
<service name="EmpService">
                                <port name="EmpServicePort" binding="tns:EmpServiceBinding">
                                                <soap:address location="http://localhost:8080/cxfsoap/emp" />
                                </port>
                </service>

The service element may contain one or more port element, where each port element represents a web service. The type attribute must have a binding reference.

Conclusion: There are two approaches for developing and publishing a web service, one is to write some Java code and then generate a WSDL document and another is to create a WSDL document first and use it for web service implementation. It will be helpful to know basic knowledge of each element for second approach of web service development. Knowing about different elements of WSDL document will help us in defining WSDL document and help us in effective debugging.

Tuesday, 17 December 2013

Profiling Java Application using annotation

This blog will provide details of measuring a performance of a code snippet while developing. This is will very handy to developer to quickly measure the performance of a method while unit testing.

Benefits:
While developing a feature a developer usually missed out performance parameter which is equally and important nonfunctional requirement.  Ideally a developer must make it as a practice to test performance of their code along with unit testing and improved it if it is not fall under acceptance criteria. A quick measurement of performance is to check the elapse time of a method. Most of the time we monitor elapse time using System.currentTimeMillis method.  But for this we need to add unwanted statements in our code. Moreover along with elapse time sometime we also required some further information like mean, minimum, maximum, standard deviation and transactions per second over a set time span.

All above task for testing performance can be easily carried out by using perf4j API. It provides us some annotation placing which we can profile our code and can get statistic in log statement. We can turn off profiling any time by removing annotation. It is quicker method to profile code snippet along with unit testing.

How to use:
Integrating perf4j API with a project is very easy. Below are steps to integrate Perf4j with a maven project. 

Add following dependency to your pom.xml. If you are integrating in an existing project then you may have some of them already in your pom.xml
<dependency>
        <groupId>org.perf4j</groupId>
        <artifactId>perf4j</artifactId>
        <version>0.9.16</version>
        <scope>compile</scope>
    </dependency>

    <!-- if you use the log4j implementation of Perf4J, you must also include this dependency -->
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.14</version>
        <scope>compile</scope>
    </dependency>

    <!-- if you use the commons logging implementation of Perf4J, you must also include this dependency -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.0.3</version>
        <scope>compile</scope>
    </dependency>

    <!-- if you use the SLF4J implementation of Perf4J, you must also include this dependency -->
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.5.6</version>
        <scope>compile</scope>
    </dependency>

    <!-- if you use also use logback as the SLF4J underlying impl, you must also include this dependency -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>0.9.15</version>
        <scope>compile</scope>
        <optional>true</optional>
    </dependency>

    <!-- if you use the AOP functionality of Perf4J, you must also include these 2 dependencies -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>1.6.1</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>commons-jexl</groupId>
        <artifactId>commons-jexl</artifactId>
        <version>1.1</version>
        <scope>runtime</scope>
    </dependency>

    <!-- if you use Spring to manage the AOP funcionality, you must also include these 2 dependencies -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring</artifactId>
        <version>2.0.6</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>2.2</version>
        <scope>runtime</scope>
    </dependency>
    <dependency>
                <groupId>org.aspectj</groupId>
                <artifactId>aspectjweaver</artifactId>
                <version>1.6.11</version>
    </dependency>

Add or append following spring configuration to project
<?xml version="1.0" encoding="UTF-8"?>

<!-- Note how the aop namespace is defined in the top-level beans element -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                           http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                           http://www.springframework.org/schema/aop
                           http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <aop:aspectj-autoproxy/>

    <bean id="timingAspect" class="org.perf4j.log4j.aop.TimingAspect"/>

    <!--
      Because we included the aspectj-autoproxy element, Spring will automatically
      create a proxy for this bean that runs the TimingAspect around any public
      @Profiled methods on this bean.
    -->
    <bean id="performanceTester" class="com.vcjain.perf.PerformanceTester"/>
</beans>

Add or append following log configuration
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration debug="false" xmlns:log4j="http://jakarta.apache.org/log4j/">
    <!--
      This default ConsoleAppender is used to log all NON perf4j messages
      to System.out
    -->
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
        </layout>
    </appender>

    <!-- Perf4J appenders -->
    <!--
       This AsyncCoalescingStatisticsAppender groups StopWatch log messages
       into GroupedTimingStatistics messages which it sends on the
       file appender defined below
    -->
    <appender name="CoalescingStatistics"
              class="org.perf4j.log4j.AsyncCoalescingStatisticsAppender">
        <!--
          The TimeSlice option is used to determine the time window for which
          all received StopWatch logs are aggregated to create a single
          GroupedTimingStatistics log. Here we set it to 10 seconds, overriding
          the default of 30000 ms
        -->
        <param name="TimeSlice" value="10000"/>
        <appender-ref ref="fileAppender"/>
    </appender>

    <!-- This file appender is used to output aggregated performance statistics -->
    <appender name="fileAppender" class="org.apache.log4j.FileAppender">
        <param name="File" value="profile.log"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%m%n"/>
        </layout>
    </appender>

    <!-- Loggers -->
    <!--
      The Perf4J logger. Note that org.perf4j.TimingLogger is the value of the
      org.perf4j.StopWatch.DEFAULT_LOGGER_NAME constant. Also, note that
      additivity is set to false, which is usually what is desired - this means
      that timing statements will only be sent to this logger and NOT to
      upstream loggers.
    -->
    <logger name="org.perf4j.TimingLogger" additivity="false">
        <level value="INFO"/>
        <appender-ref ref="CoalescingStatistics"/>
    </logger>

    <!--
      The root logger sends all log statements EXCEPT those sent to the perf4j
      logger to System.out.
    -->
    <root>
        <level value="INFO"/>
        <appender-ref ref="console"/>
    </root>
</log4j:configuration>


With above configuration you are ready for profiling. Now add @Profiled annotation to the method which you want to profile and execute code. You will receive your statistic in your log file specified in logging configuration something like below

Performance Statistics   2013-08-30 13:07:10 - 2013-08-30 13:07:20
Tag                             Avg(ms)         Min         Max     Std Dev       Count
profileTest                     2027.0        2027        2027         0.0           1


For non-maven project we can keep all dependency jars in the classpath. I have created a sample maven project to demonstrate use of Perf API. Please get the complete project from Git repository https://github.com/vcjain/perfapi.git. You can execute project using maven command mvn exec:java.