Spring JMS – Java Messaging Service explained end to end.

Hey guys, Hope you are doing well.
In this blog I will be focusing on JMS(Java Messaging Service) with an end to end Web Application.

In this process , we will be creating a demo application which will be posting message (Text message) from front end screen. This message will be used by Message producer  of JMS to post the message on the Queue.We will be using ActiveMQ as a broker here. JMSTemplate is used in this example for message Posting.Similarly on Other end on the same queue there will  be Consumer configured which will consume the message posted by Producer.The whole Message tracking will be logged in a separate Logger named JMSDemo.log in logs directory of your application server.

The tools and techniques used in this project are mentioned below:

  •  STS 3.5.0 (Spring Tool Suite)
  •  apache-activemq-5.9.0
  •  Apache Maven 3.1.1
  •  Springs
  •  Tomcat 7
  •  JDK 1.6

Lets Begin, Below are the steps which describes the implementation.


Step 1> Download apache-activemq-5.9.0 from below link and install on your local machine.
http://activemq.apache.org/activemq-590-release.html

After downloading , execute activemq batch file under bin folder (directory win32/win64).

This will start the ActiveMQ and at the end the URL from which we can access it will be seen in logs.
Please refer below screen shot for reference

ActiveMQ_start

On the browser please verify by hitting below URL:
http://localhost:8161/admin/queues.jsp

by default username password is : admin/admin

Step 2> Create a Maven Project with below artifacts information

<groupId>com.x.jms.JMSDemo</groupId>
<artifactId>JMSDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>JMSDemo</name>
<description>JMSDemo</description>

Step 3> Update the pom.xml
Add the below dependencies and plugins in the pom.xml

pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.x.jms.JMSDemo</groupId>
<artifactId>JMSDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>JMSDemo</name>
<description>JMSDemo</description>

<repositories>
<repository>
<id>java.net2</id>
<name>Repository hosting the jee6 artifacts</name>
<url>http://download.java.net/maven/2</url&gt;
</repository>
</repositories>

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<!– <version>3.0.5.RELEASE</version> –>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-all</artifactId>
<version>5.9.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>

<build>
<finalName>JMSDemo</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-beta-1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</build>
</project>

Step 4> Create a folder Structure as mentioned in screenshot

Folder_Structure

Step 5> com.x.jms package files

ConsumerTask.java   [Used to Consuming Messages from the Queue]
file: ConsumerTask

ProducerTask.java   [Used to Produce Messages on to the Queue]
file:  ProducerTask

RequestHandlerServlet.java   [Servlet which delegates User Request as a message to ProducerTask]
file: RequestHandlerServlet

Note: Please change the file extension as required.

Step 6> Configuring Spring-config ,context ,log4j ,web.xml  file.

spring-config.xml   [bean definitions of Producer and Consumer files along with jmsTemplate]
file:  spring-config

context.xml   [Consist of resources of mqConnectionFactory and Destination details]
file: context

log4j.properties[Logging information and patterns used of logging]
file: log4j

web.xml
file: web_JMSDemo

Note: Please change the file extension as required.

I wont be explaining webapplication related stuff like JSP and Servlet ,since they are complementary in this space and used to
test JMS stuff.

Step 7>  jsp files

index.jsp [ Used to Post messages from front end]

index

success.jsp

success

Step 8> Add ActiveMq jar in lib folder of Tomcat Lib directory
jar name: activemq-all-5.9.0.jar

Step 9> Build and deploy the project
copy the war file from target folder and deploy it to Tomcat webapps directory, and start the Tomcat server.

Step 10> Verify the web application

Go to the browser and hit http://localhost:8081/JMSDemo/  this should open an UI to post message.
Add some text in there and click POST MESSAGE button to post the message to the Queue.
As for this example i have posted Testing Spring JMS message .
Please verify the message trace in JMSDemo.log in logs directory. Below is the screenshot which verifies the same.

Note: Please mention port name in URL as per your server running on.
Verification

Advantages of using JmsTemplate is that its very easy to implement and encapsulate the traditional code of creating ConnectionFactory, Connection, Session, MessageProducer, MessageConsumer, TextMessage etc .

I am done with this article, will be back soon with some more interesting topics, till then enjoy coding🙂

Enabling SONAR for your existing Maven project in Simple steps.

Hey friends, with reference to my previous blog , link  https://pranavkuthe.wordpress.com/2014/08/22/my-software-lab/ there i have mentioned about SONAR for code analyses.
In this blog i will be Embedding SONAR with our Maven Project.

Sonar is tool which analyse the project code and generate reports .
These reports shows the Violations, Rule Compliance, Unit Test Coverage, Classes, Lines of code etc information about the deployed project.

With the help of these reports the code can be re-factored precisely, which improves the health of the system overall.

Doing configuration for an existing project is very simple and is shown below .
To make it look easier i will be enabling SONAR for my project in first blog link https://pranavkuthe.wordpress.com/2014/08/08/maven-jax-ws-webservice-top-to-down-approach-fetching-complex-details/


Step 1)  Download SONAR 

Please download the SONAR from below link .

http://dist.sonar.codehaus.org/sonar-3.5.1.zip

After downloading the zip file, Unzip the folder in to your destination where you would like to install SONAR.

After extracting the file please go inside below directory

drive: \sonar-3.5.1\bin\windows-x86-64

and execute StartSonar windows batch file.

The above installation is been done for Windows 64 bit OS (which is on my local🙂 )

Note:  For Environment specific installation execute respective file like for linux-x86-64 machine run sonar.sh shellscript.

After running the batch file for windows, the message like below can be seen.

……

…..

jvm 1 | 2014-08-27 23:47:05.285:INFO::Logging to org.sonar.application.Filter
edLogger@1630ab9 via org.sonar.application.FilteredLogger
jvm 1 | 2014-08-27 23:47:05.325:INFO::jetty-6.1.25
jvm 1 | 2014-08-27 23:47:05.436:INFO::NO JSP Support for /, did not find org.
apache.jasper.servlet.JspServlet
jvm 1 | JRuby limited openssl loaded. http://jruby.org/openssl
jvm 1 | gem install jruby-openssl for full support.
jvm 1 | 2014-08-27 23:47:28.049:INFO::Started SelectChannelConnector@0.0.0.0:
9000

 

Now you can browse your sonar installation http:localhost:9000

You will be able to see the Dash Board here.

 

Step 2)  Update the pom.xml file for the project with below lines.

Please update pom.xml with the property in green.

pom.xml

 

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.x.customer</groupId>
<artifactId>CustomerService</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>CustomerService</name>
<description>CustomerService</description>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.host.url>http://localhost:9000/</project.host.url&gt;
<sonar.exclusions></sonar.exclusions>
</properties>

<dependencies>
<dependency>

………

…….

……

 

Save the pom.xml file

 

Step 3) Generate the report 

  • Open cmd and Goto the path where your project is created. Like my project is created in below location “F:\STSWorkSpace\CustomerService”.
  • From cmd  execute command mvn sonar:sonar

This will Analyse the project  and build it. The trace can be seen like below

 

…………….

………….

……….

[INFO] [00:39:29.385] Sensor JaCoCoSensor…
[INFO] [00:39:29.392] Project coverage is set to 0% as no JaCoCo execution data
has been dumped: F:\STSWorkSpace\CustomerService\target\jacoco.exec
[INFO] [00:39:29.548] No information about coverage per test.
[INFO] [00:39:29.549] Sensor JaCoCoSensor done: 164 ms
[INFO] [00:39:29.759] Execute decorators…
[INFO] [00:39:31.760] Persist graphs of components
[INFO] [00:39:31.912] ANALYSIS SUCCESSFUL, you can browse http://localhost:9000
[INFO] [00:39:31.913] Executing post-job class org.sonar.plugins.core.batch.Inde
xProjectPostJob
[INFO] [00:39:31.969] Executing post-job class org.sonar.plugins.dbcleaner.Proje
ctPurgePostJob
[INFO] [00:39:31.978] -> Keep one snapshot per day between 2014-07-31 and 2014-0
8-27
[INFO] [00:39:31.979] -> Keep one snapshot per week between 2013-08-29 and 2014-
07-31
[INFO] [00:39:31.980] -> Keep one snapshot per month between 2009-09-03 and 2013
-08-29
[INFO] [00:39:31.981] -> Delete data prior to: 2009-09-03
[INFO] [00:39:31.985] -> Clean CustomerService [id=27]
[INFO] [00:39:31.989] <- Clean snapshot 69
[INFO] ————————————————————————
[INFO] BUILD SUCCESS
[INFO] ————————————————————————
[INFO] Total time: 29.834s
[INFO] Finished at: Thu Aug 28 00:39:32 IST 2014
[INFO] Final Memory: 20M/254M
[INFO] ————————————————————————

 

Now verify by hitting http://localhost:9000

Screenshot below verifies the same.

Screenshot 1: CustomerService project can be seen in this screen.

Screenshot1

 

Screenshot 2:

Report Analysis of CustomerService project.

Screenshot2

 

Cool… I am done with this post , will be back soon with many more interesting topics .

Till then Enjoy Coding🙂

 

My Software Lab

Hey Friends, This time its a Code Free Blog.
Last week was really hectic for me… was bit tired and thought of writing something new.
Well Software Industry is not just all about coding🙂

Through out my whole career till now, I met many talented and Genius people , worked with them and learnt a lot and guess what, i am still learning.
This learning process continuously get evolved by time and kept us learning more.

Global Software Industry as it rises to new level it brings more Challenges , people tries there best to achieve best, and this is a never ending process.

In our day to day professional life, we do many things. We gather requirements, prepare design docs, Code, test , release any many more things.No matter how much effort it takes to build a functionality or a product at the end what matters the most is delivery.

My views in this blog will specifically focused on Software Delivery , and the process involved in it.

All of us in some point of time or on daily basis are accustomed to hear words like

What the status of your work ?
Is the Code ready for Delivery ?
We have a change in requirement in middle, and same needs to be incorporated in the same release.
You have to deliver this week no matter what it takes you to do it.
Fix all the bugs before weekend…

Well if we plan our work, our deliverable s, all above things should be avoided. These and many more serious stuff can be managed by applying proper techniques.

AGILE principle work’s awesome in most cases.

Techniques like SCRUM, KANBAN, Extreme Programming (XP) comes in to rescue.

AGILE has really got matured and fits into most of the projects.
We now often see White boards with different colored sticky on it describing various task and work.
Every team has at least one of these board to track there daily work. People gathering on daily basis around these boards and updating there daily tracker.

Three points to discuss by every team member.

  • What you did yesterday?
  • What you are going to do today ?
  • Are there any Impediments ?

In our understanding, its must be hard-wired that Definition of Done means its delivered to client.
Our functionality is serving our clients, and the business expectations are met as planned.

Software delivery comes through various phases and there are separate challenges in all phases.
I have put forth my views on these phases and how they can be handled in a better way.

Requirement Gathering :
I think for me its the most important part of the life cycle. Its holds the key to build a road map and strategies involved. There are many cases where we blame incorrect requirements for any failures.

Issues faced here includes
a) Poorly maintained backlog and most of the cases are pending from years.
b) Only BA’s are involved to get requirements which is asking for trouble.

Poorly maintained backlogs can create lot of confusion in team and hence these backlogs must be discussed with Business Owner/Client and must be re-written in  very precise manner.

  • Like as a Client what client expects ?
  • And As a end product what we will deliver ?

Are both the points tending to deliver the same. And if they are your backlog is fine.

AGILE is all about People. Our second problem can be solved by making your team-mates involvement in the process.
While Requirement gathering we must involve all the team members including Testers, Developers, BA’s and Managers.
The code is not just delivered by Developers but it comprises efforts involved by whole team.

We deliver as a team, We Succeed as a Team , We fail as a team. No blame game here.

This builds the most interesting part of the life cycle, i.e TRUST in the team. If we trust each other we can deliver everything.
Involving other people in the client requirement can clear the doubts instantly.

Functional view’s of a BA, or a Tester, or a developer can clear the doubts and can raise the questions to our business owner if any thing can be done more better which many time clients applauds and this improves the TRUST with client
and most important within the team.

Planning:
Most existing part of the life cycle.

General issues faced here are
a) Priorities of task to be done.
b) The sequence in which the tasks needs to be done.

Solution here is simple, as we been through with our Requirement gathering, we now must prioritize the functionalities.
Firstly any functionality which needs to be delivered must have a client priority.
As per priority we can pull as much functionalities into our current Sprint.
The amount of work been pulled in sprint depends on your team capacity which is defined by a current team strength and task per person per day can do. I wont go in deep how to define total team strength. Experience in this AGILE process makes things easier in this case.

In Team meeting we then finalize the points (Efforts in Person Days (PD)) required to complete each functionality. Its better to break down the functionalities in to smaller tasks when the per person effort goes above 3(PD) or 5(PD). This is to ensure work is done smoothly , and minimize the risk in development phase.
The figure 3 and 5 comprises functionality will successfully complete initial analysis, Development, and Testing.

Next problem ,The sequence how we deliver is very important.
As mentioned above we have broken down our task (analysis,development,testing per functionality) into smaller parts but how they must be arranged so that no part of functionality should affect other team members in there work in current sprint. To solve this, Team comes to rescue. We can sort all the sequence of deliverable’s with team in our planning sessions. Once we have sorted the sequence of deliverable s we finally prepare White board.

White board will have task for every person per day who is involved in the sprint. The task can be referred with different colors of sticky for different teams (Analysis,Development, Testing). This way right from first day of Sprint all members of the team are aware what they have to do everyday of sprint.

Development :
Our Bread and Butter🙂

As a developer we must follow best industry standards. Every thing in the human space made by humans needs maintenance, and code is no longer an excuse.
It doesn’t means if the part of the code which is already in production few months ago and working perfectly fine doesn’t needs maintenance. As we do re-factoring of the existing code it increase the life of the application, which on longer terms saves lot of cost. Writing down test cases for every single line may appears to be big task for developers initially, but it will be fine if we make it as an habit in our development life cycle.This will definitely raise our bar. There are various advantages of writing down test cases. Writing down test cases makes our code testable , more object oriented and most importantly we build code for what it is been coded for (Test cases specific to it needs).
We must incorporate Continuous Integration techniques (Jenkins,Hudson etc) , code analysing tools (Sonar etc) and automatic Database scripts deployment through automated deployments.

The developer should code in a fashion that anybody in the team can do a deployment on a single click of a button. This is very much possible by using above techniques and tools. This will reduce the deployment dependencies. Any problems faced can be reverted back again through single click of a button which will revert all the changes within few seconds.

Testing:

Complete application must be tested automatically along with some manual testing where it needs. Most of the scenarios in the application carries similar sort of testing. These steps must be automated to shorten the life cycle of testing and most important effectively.
So apart from manual testing, automated testing plays a crucial role in a successful software delivery.

AGILE is so famous , and one of the reason it is because through AGILE we can deliver quickly. Through AGILE anyone can deliver ” Minimal Viable Product ” very effectively if it is correctly implemented and followed by the people.

Release:

Release is the final stage which must be quick, so as to ensure least downtime. Today top Software companies have achieved nearly or Zero down time through smart models which incorporates to take changes Live without making your Production Server down. By managing our servers in cluster environment and through routing devices this can be achieved.

Our  environments should be build in such a way that every day we can release the code in to production environment. That kind of flexibility should be achieved.

To deliver more with rapid pace without sacrificing the quality and without any downtime its not a dream but its an reality today.

This Knowledge based industry keeps on surprising billions of people making there day to day life easier.

Many things to say but for this blog i would like to conclude.

Hope this blog somehow helps you .Will be back soon till then Cheers🙂

REST Web service (JAX-RS) using Jersey ,JAXB , Maven and Service Client.

Hi All,

In this article we will be designing services in the REST form.
REST stands for Representational State Transfer which is a architectural pattern and very much popular(JAX-RS).
In this example we will be looking few glimpses of the same .

I have mentioned few steps to create a simple REST service. To keep it simple below service cater on GET operation.


Step 1) Creating a Maven Project with below artifacts information

<groupId>com.x.rest.service</groupId>
<artifactId>RestService</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>RestService</name>
<description>RestService</description>

This will create your Project in STS(Spring Tool Suite).

Step 2) Update the pom.xml

pom.xml will be updated with dependencies and the plugins as needed. We will be incorporating “maven-compiler-plugin” and “maven-war-plugin” in pom.xml.

pom.xml

Note : Please check attached pom.xml file. Copy the content and rename it to pom.xml.

RestService_pom

Step 3) Create a folder structure

Note : Please check attachment for the respective files. Copy the content and rename it accordingly.

Add few packages under src/main/java and the classes inside it

com.x.rest

  • UserInformation.java  (annotate this class with javax.ws.rs  notations.)   UserInformation

This class is responsible for handling client requests. If we note carefully , in this class and its specific methods are identified by @Path  annotation. So as per REST pattern we are identifying each method as a resource and all these resources are been identified through a URL. The responsibility of these resources is to provide pure data only . But how to use/show that data depends upon the client implementation.

com.x.rest.model

  • ClientBankDetailsBean.java  (This bean stores information of Client Bank Details)  ClientBankDetailsBean
  • ClientDemographicDetailBean.java (This bean stores information of Client Demographic Details)  ClientDemographicDetailBean
  • UserInfoHelper.java (POJO which uses above two beans and talks to the service)  UserInfoHelper

Under webapp directory create folder

WEB-INF 

under WEB-INF directory create lib directory.

Inside lib directory add jersey distribution jars. These jars can be downloaded from below link

http://jersey.java.net/

Step 4)  Build the WAR file and Deploy in Tomcat(7) webapps directory

Run mvn clean and install command to create WAR file . Deploy the war in Tomcat webapps directory and start the server.

Step 5) Verify the Service response by hitting the specific URLs.

In this case hit below two URL’s .

To fetch Demographic Details

To fetch Bank Details

Note :  Please change the port number as per your machine port on which Tomcat server running.

This makes your Service ready. Now to write a client and consume the service is even easier. Please refer below steps

Step 6) Creating Client.

Please create a new Maven Project with below artifacts information

<groupId>com.x.rest.client</groupId>
<artifactId>RestServiceClient</artifactId>
<version>1.0-SNAPSHOT</version>
<name>RestServiceClient</name>
<description>RestServiceClient</description>

This will create your Client Project on STS.

Step 7) Update pom.xml file

Please see the pom.xml file as below

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.x.rest.client</groupId>
<artifactId>RestServiceClient</artifactId>
<version>1.0-SNAPSHOT</version>
<name>RestServiceClient</name>
<description>RestServiceClient</description>
<dependencies>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.8</version>
</dependency>
</dependencies>
<build>
<finalName>RestServiceClient</finalName>
</build>
</project>

Step 8) Create packages and classes to access the client

Note : Please check attachment for the respective files. Copy the content and rename it accordingly.

create below package under src/main/java

  • com.x.rest.client.constant
  • com.x.rest.client.main

Under constant folder create one java class as RestServiceClientConstants.java (This class holds the information of URL in the form of constants)  RestServiceClientConstants

Under main folder create one java class as RestServiceClient.java (This class is the client class which consumes the RestService) RestServiceClient

Step 9) Run the Client

Please run the RestServiceClient.java  file and see the output in console (Ensure the RestService is up and running before executing client code)

Output:

21 Aug, 2014 2:32:57 AM com.x.rest.client.main.RestServiceClient main

INFO: DEMOGRAPHIC INFO URL:GET http://localhost:8081/RestService/rest/UserInfoService/demographic/1 returned a response status of 200 OK
21 Aug, 2014 2:32:57 AM com.x.rest.client.main.RestServiceClient main
INFO: BANK_DETAIL INFO URL:GET http://localhost:8081/RestService/rest/UserInfoService/bankdetail/1 returned a response status of 200 OK
21 Aug, 2014 2:32:57 AM com.x.rest.client.main.RestServiceClient main
INFO: Response DEMOGRAPHIC:<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
<ClientDetails>
<name>Pranav</name>
<address>Airport Road</address>
<city>Pune</city>
<phone>9878686868</phone>
<zipcode>435739</zipcode>
<country>India</country>
</ClientDetails>

21 Aug, 2014 2:32:57 AM com.x.rest.client.main.RestServiceClient main
INFO: Response BANK_DETAIL:<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
<ClientBankDetails>
<bankname>Bank of ABCDF</bankname>
<bankbranch>Fort</bankbranch>
<bankaddress>Mumbai</bankaddress>
<bankaccount>4353453543</bankaccount>
<accountbalance>967836339.73</accountbalance>
</ClientBankDetails>

That’s it from my end on REST Websevices. I will be back soon with a new topic till then enjoy coding🙂

Developing JAX-WS Client using Maven.

Hi all nice to be here again,

With reference to my first blog “Maven, JAX-WS WebService Top to Down Approach – Fetching Complex details.
link: – https://pranavkuthe.wordpress.com/2014/08/08/maven-jax-ws-webservice-top-to-down-approach-fetching-complex-details/

I would like to present next part which is the simplest among both. Its about  developing JAX-WS Client to consume service.
The client is the mediator between a service and any application which uses that service.

So without wasting any time lets code..


Step 1) Create a Maven project in STS

Note: The project should be build as a jar hence select packaging as jar.

Please provide below artifacts information while creating a project
<groupId>com.x.ws.client</groupId>
<artifactId>CustomerServiceClient</artifactId>
<version>1.0-SNAPSHOT</version>
<name>CustomerServiceClient</name>
<description>CustomerServiceClient</description>

This will create a Maven Client Project.
Step 2) Create the folder structure for client.

Under src/main/java add package com.x.ws.generated

Under resources folder add two folders

  • wsdl
  • xsdAfter creating above folder structure add the two xsd’s (CustomerDetails.xsd,soap-encoding.xsd) and wsdl (customer.wsdl) file in there respective folders created from our previous project.

Step 3) Update the pom.xml file for client.

Plugins remain the same except we will not be using maven-war plugin here. I have pasted my client pom.xml below.
Also note that in jaxws-maven-plugin below we have carefully added the exact path for <wsdlDirectory> and <packageName> as we have created in above step.
In absence of proper path the build will fail.
We will be using wsimport to generate all the artifacts related to mentioned wsdl in wsdl directory.
Another popular way of generating artifacts is via command prompt. But In this case maven made that task easy for us🙂

pom.xml

<project xmlns=”http://maven.apache.org/POM/4.0.0&#8243; xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”&gt;
<modelVersion>4.0.0</modelVersion>
<groupId>com.x.ws.client</groupId>
<artifactId>CustomerServiceClient</artifactId>
<version>1.0-SNAPSHOT</version>
<name>CustomerServiceClient</name>
<description>CustomerServiceClient</description>
<dependencies>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>2.1.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>CustomerServiceClient</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${basedir}/src/main/java</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>jaxws-maven-plugin</artifactId>
<version>1.12</version>
<configuration>
<wsdlDirectory>${basedir}/src/main/resources/wsdl</wsdlDirectory>
<packageName>com.x.ws.generated</packageName>
<keep>true</keep>
<sourceDestDir>${basedir}/src/main/java</sourceDestDir>
</configuration>
<executions>
<execution>
<goals>
<goal>wsimport</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

Step 4) Now do a mvn clean and then mvn install.

This will generate the artifacts in desired folders.

Step 5) Create a handler which will be call by other Applications to access the service.

create a package com.x.ws.impl
create a java class in the package created above “CustomerServiceClient.java

Add the below code in above created java class.
CustomerServiceClient.java

package com.x.ws.impl;

import com.x.ws.generated.CustomerPort;
import com.x.ws.generated.CustomerResponse;
import com.x.ws.generated.CustomerService;
import com.x.ws.generated.SearchInput;

import java.util.logging.Level;
import java.util.logging.Logger;

public class CustomerServiceClient {

private final static Logger logger = Logger
.getLogger(CustomerServiceClient.class.getName());

public CustomerResponse getCustomerData(SearchInput input) throws Exception {

CustomerResponse customerResponse = new CustomerResponse();
CustomerService customerService = new CustomerService();
CustomerPort customerport = null;

try {
customerport = customerService.getInformation();
customerResponse = customerport.getCustomerData(input);
} catch (Exception ex) {
logger.log(Level.INFO, “ERROR:” + ex.getMessage());
throw ex;
}

return customerResponse;
}

}

Step 6) perform mvn clean and then mvn install .

To test this client you have to start the service which we have created in our previous blog.
And in above class CustomerServiceClient.java add one main method which is calling getCustomerData(SearchInput input) ,
and add few loggers to check information is been pulled out from service layer successfully or not. But one should remove main method after testing(as it is not recommended) or one should write a test case to test our client.

Note : while running client if you face issue like “Unsupported Content-Type: application/soap+xml Supported ones are: [text/xml] “. Do the below fix.

Fix:
In our customer.wsdl file in both projects (client,service) add the url of the webservice in soap:address location part.
I have added below code on my local. Again add the port specific to your local machine on which your server is running.
After doing this do mvn clean and mvn install on both the projects and redeploy your service project in Tomcat. This time it should run.

Changes done in red.

<wsdl:service name=”CustomerService”>
<wsdl:port binding=”tns:CustomerService” name=”Information”>
<soap:address location=”http://localhost:8080/CustomerService/CustomerService” />
</wsdl:port>
</wsdl:service>

Now once this client is created successfully and working fine, we can import this jar in the applications which needs to access these services. We will add the client jar in dependency of that application pom.xml file and call the getCustomerData method in client jar that’s it.

I will post many more topics going forward till then enjoy coding…..  cheers🙂

Maven, JAX-WS WebService Top to Down Approach – Fetching Complex details.

Hi All, This is my very first post on this blog, and we will understand JAX-WS webservice with top to down approach.

Here we have used JAX-WS. JAX-WS uses technologies defined by the W3C : HTTP, SOAP, and WSDL. WSDL is nothing but an XML format which describes the service as a set of endpoints operating on a message.

Before Starting please see below tools/softwares used for this example.

  •  JDK 1.6
  •  STS 3.5.0 (Spring Tool Suite)
  •  Apache Maven 3.1.1
  •  Tomcat 7
  • SOUP UI 4.5.2 ( Developing Client using JAX-WS will look in my next post of JAX-WS Client coding. To make it look easy we will use SOUP UI tool here. )

The Project we will be developing here is to fetch Company Details which includes its demographic profile and Financial Information which includes its Balance Sheet Details.

Lets hit the code now….


Step 1)  Create a new Maven Project name CustomerService in STS. Provide the Artifacts information as below

<groupId>com.x.customer</groupId>
<artifactId>CustomerService</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>CustomerService</name>
<description>CustomerService</description>

After providing above details , Project will be created in your STS.

Step 2) Update the pom.xml file.

As we are using packaging as WAR as shown above, we have to use Maven Plugin which will be used for Code Compilation, WAR Plugin, Build Help Maven Plugin along with some dependency Jar file. I have attached the pom.xml file as below.

pom.xml

pom

 

Step 3) Update the Folder Structure

We have to add few new folders to make our work more manageable.

Please Add two folders inside resources folder.

  • xsd
  • wsdl

Please Add one folder under webapp folder.

  • WEB-INF

 

Step 4) Creating a XSD file and our WSDL contract file.

Under XSD folder will be creating two files

  • CustomerDetails.xsd  (This will have our Request and Response details).
  • soap-encoding.xsd (Schema for the SOAP/1.1 encoding).

User WSDL folder

  • customer.wsdl

I have attached these three files below

CustomerDetailsXSD

soap-encodingXSD

customerWSDL

Note : Please copy the content from above files and save with proper extensions as mentioned above.

Step 5) Run the Maven Clean and then Install command.

This should generate all the artifacts related to XSD’s. These are required to write an implementation class for the webservice.

 

Step 6) Write the WebService Implementation Class

Web Service Implementation class will be responsible to cater the request and send the response to the caller.

Before creating a Implementation class, we will create a new package as impl  under com.x.ws folder.

so the structure now looks like

com.x.ws.generated

com.x.ws.impl

under impl package create one class named as  CustomerServiceImpl.java 

Referring the CustomerDetails.xsd we have to set responses in there desired objects. These objects are already been generated by maven install command.

In normal application we will fetch the details of request either from a Database or a file system and then set the responses, but here for simplicity i have hard coded the values directly in our impl class .

I have attached this class below.

CustomerServiceImpl_JAVA

Note : Please copy the code in above created class with proper extension.

 

Step 7) Last but not Least , Adding web.xml and sun-jaxws.xml files under WEB-INF folder

I have pasted code for above two files below.

web.xml

<?xml version=”1.0″ encoding=”UTF-8″?>
<web-app xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance&#8221;
xmlns=”http://java.sun.com/xml/ns/javaee&#8221; xmlns:web=”http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;
xsi:schemaLocation=”http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;
id=”WebApp_ID” version=”2.5″>

<display-name>CustomerService</display-name>

<listener>
<listener-class>com.sun.xml.ws.transport.http.servlet.WSServletContextListener</listener-class>
</listener>
<servlet>
<servlet-name>CustomerService</servlet-name>
<servlet-class>com.sun.xml.ws.transport.http.servlet.WSServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CustomerService</servlet-name>
<url-pattern>/CustomerService</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
</web-app>

 

sun-jaxws.xml (Your mapping file which has entry of Implementation class)

 

<?xml version=”1.0″ encoding=”UTF-8″?>
<endpoints xmlns=”http://java.sun.com/xml/ns/jax-ws/ri/runtime&#8221;
version=”2.0″>
<endpoint name=”CustomerService” implementation=”com.x.ws.impl.CustomerServiceImpl”
url-pattern=”/CustomerService”></endpoint>
</endpoints>

Step 8) Building Project

Hit Maven clean command, then Maven Install. This will generate “CustomerService.war” file in target folder.

 

Step 9) Deploy war file in Tomcat

Please deploy this CustomerService.war in deploy folder of Tomcat server.

path : ∼/apache-tomcat-7.0.54/webapps   and run  windows startup.batch file inside bin directory of tomcat server.

This will start the tomcat and your war will be deployed.

You can check your browser by hitting below url.

http://localhost:8080/CustomerService/CustomerService?wsdl

Note: The port 8080 is a default port on my tomcat. Please put respective port from your machine on which tomcat is running.

This url will make us aware that service is up and running.

Note :  Incase any problems while starting server add a lib folder under WEB-INF and put all JAX-WS specific jars in it. These can be downloaded from internet. You can search for jaxws-ri-2.2.8   jars.

Step 10)  Open Soap UI and create a project .

In SOAP UI tool create a new project by passing above url. This will create a request.

Fill that request (input) and click submit request. This will invoke the impl class and get the response back .

I have attached the snapshot of request and response below.

 

Request:

<soapenv:Envelope xmlns:soapenv=”http://schemas.xmlsoap.org/soap/envelope/&#8221; xmlns:cus=”http://com.x.customer/CustomerDetails”&gt;
<soapenv:Header/>
<soapenv:Body>
<cus:SearchInput>
<cus:id>1</cus:id>
</cus:SearchInput>
</soapenv:Body>
</soapenv:Envelope>

Resposne:

<S:Envelope xmlns:S=”http://schemas.xmlsoap.org/soap/envelope/”&gt;
<S:Body>
<CustomerResponse xmlns=”http://com.x.customer/CustomerDetails&#8221; xmlns:ns2=”http://schemas.xmlsoap.org/soap/encoding/”&gt;
<compName>India Steel and Forge</compName>
<compRegisteredName>India Steel and Forge Pvt Ltd</compRegisteredName>
<Addresses>
<Address>
<line1>India Steel and Forge Pvt Ltd</line1>
<line2>MIDC Road</line2>
<city>Pune</city>
<state>Maharashtra</state>
<zipCode>441234</zipCode>
<Phones>
<Phone>
<countryCode>91</countryCode>
<cityCode>022</cityCode>
<number>0758565657</number>
</Phone>
<Phone>
<countryCode>91</countryCode>
<cityCode>022</cityCode>
<number>8984937979</number>
</Phone>
</Phones>
</Address>
</Addresses>
<FinancialDetails>
<custIncome>25000.0</custIncome>
<custIndustryType>Steel and Forge</custIndustryType>
<custTaxPaid>5000.0</custTaxPaid>
<custIncomeCurrency>USD [$]</custIncomeCurrency>
<custBalanceSheet>
<custAssets>
<compBuilding>400000.0</compBuilding>
<compLand>100000.0</compLand>
<custAssetsTotal>500000.0</custAssetsTotal>
</custAssets>
<custLiabilities>
<mortGage>300000.0</mortGage>
<equity>200000.0</equity>
<custLiabilitiesTotal>500000.0</custLiabilitiesTotal>
</custLiabilities>
</custBalanceSheet>
</FinancialDetails>
</CustomerResponse>
</S:Body>
</S:Envelope>

 

That’s it from my end on this opening blog of mine. Hope it helps. Please write to me with your own experiences/opinion/suggestions🙂