Sunday, November 10, 2013

How to debug your applications built by custom ant builds in Intelij Idea

Sometimes things which looks very minor end up taking more time than expected. My transition to Intelij idea from eclipse was pretty smooth with an exception to debugging. In the good old days I was using tomcat as server and eclipse as IDE. Just with a tomcat plugin for eclipse I was able to debug my code. 
Expecting the same and reluctant to use the ant auto generated by intelij idea I wrote my own ant build and wrote some code.After the sweet message "build successful", I deployed it on jboss. Tried to debug the code by placing a break point which to my surprise never reached. After many long hours of experimenting I added debug attribute and turned it on in javac ant task and bingo!!! debug point reached. Hope this saves your time!!!
Happy debugging!!! :)
 

Sunday, September 8, 2013

SHA-256 in JAVA


Note: For mobile users, kindly switch to web version on your mobile.
Security is a very basic requirement which every developer has to keep in mind while designing or developing an application. I would like to take this opportunity to quote a line from the one of the book I read "Every system can be broken, given enough time and money. Let me say that again, every system can be broken". This very quote itself inspired me to blog a series of tutorials regarding security, cryptography and what else is the best place to start other than SHA-256. In the near future I will try to blog more tutorials on digital signatures, how to verify digital signatures, digital certificates based authentication, Keys .....
SHA-2
For a given input SHA-256 will generate a hash value through which the input can be validated and guaranteed that its contents are not tampered. Sender can generate a hash value and share it with the receiver through which receiver can validate the file. If the contents of the file is changed the hash value will also change.(This is what we basically see on many download sites). Below is an example using Message Digest.

SHA256Example.java
package itsvenkis.blogspot.in;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA256Example {

 public static void main(String args[]) {
  FileInputStream fis = null;
  try {
   File file = new File("files.txt");
   if (!file.exists() || file.length() == 0) {
    throw new RuntimeException("Bad input................");
   }
   fis = new FileInputStream(file);
   byte[] fileBytes = new byte[(int) file.length()];
   MessageDigest md = MessageDigest.getInstance("sha-256");
   int length;
   while ((length = fis.read(fileBytes)) != -1) {
    md.update(fileBytes, 0, length);
   }
   byte[] raw = md.digest();
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < raw.length; i++) {
    byteToHex(raw[i],sb);
   }
   System.out.println("hash value in HEX " + sb.toString());
  } catch (NoSuchAlgorithmException | IOException e) {
   e.printStackTrace();
  } finally {
   if (fis != null) {
    try {
     fis.close();
    } catch (IOException e) {
     e.printStackTrace();
    }
   }
  }
 }

 private static StringBuilder byteToHex(byte b, StringBuilder sb) {
  String hexVal = Integer.toHexString((b & 0xff));
  if (hexVal.length() == 1) {
   return sb.append("0").append(hexVal);
  }
  return sb.append(hexVal);
 }

}

files.txt
itsvenkis blogspot

Output:
cc439a348e5f91e483c9c6c3620ec5b38ee18ce78ff82ccce07aba4493519f70
Dear Readers, kindly like the page on facebook or follow me on Google+.

Friday, September 6, 2013

JMS REST tutorial - HORNETQ REST Interface tutorial


Introduction
HORNETQ is the defualt messaging system provided by JBOSS Application Server. In one of my previous tutorial I covered how to configure, produce and consume Messages through JMS API using HORNETQ as provider. You can find the tutorial @ HERE.
NOTE: This tutorial uses queue named 'restInterfaceQueue'. To know how to create this queue please take a look into the above tutorial.
This tutorial will focus on creating and consuming messages from HORNETQ using REST API.
Why would one ever need to produce and consume messages through REST?
Well!!! I would say to support CROSS LANGUAGE CLIENTS.... and also to provide web based API for messaging. With these capabilities one no longer needs producer and consumer to be through JMS API. So anyone who understands HTTP can produce and consume messages. This one big advantage of REST interface. HORNETQ provides a very good REST interface. Some of the features of REST interface provided by HORNETQ are given below
  • Avoid posting of duplicate messages
  • Mix and match JMS and REST producers and consumers
  • Acknowledgement and auto acknowledgement 

Technologies Used
  • JAVA 
  • J2EE
  • RESTEasy
  • HORNETQ 
  • HORNETQ REST Interface
  • Maven  

Coplete list of features and more information about REST interface and HORNETQ can be found @here. Lets get started!!!! 
Boot strapping HORNETQ with REST
To use HORNETQ REST interface in our application we first need to bootstrap it. This can be done by adding the below listener in web.xml

  org.hornetq.rest.integration.RestMessagingBootstrapListener
 

REST Interface Configuration
We should add some configuration information for REST interface. This can be done in an xml file under WEB-INF/classes. The name of the file should be mentioned in web.xml using rest.messaging.config.file context param

hornetq-rest.xml

   0
   false
   true
   
   true
   topic-push-store
   queue-push-store
   10
   1
   300
   0
The entries in above XML file are explained below
Server-in-vm-id : This is to differentiate different HORNETQ servers running in
same VM. We can default it to zero
Use-link-headers: To tell HORNETQ how to publish the links. By default it publishes
using cutoms headers. This tutorial uses the default behaviour so we can mark it as
false
default-durable-send: Used to identify if the posted message needs to persisted in
DB.We will mark it as false. This default behaviour can be overriddden by sending
durable custom header as true
dups-ok Should duplicate messages be allowed?
client-window-size Used to identify buffering capabilities. By specifying it as zero we are saying we don't want any buffering to happen for delivery of messages.
Now lets take a look at our complete web.xml


 
  rest.messaging.config.file
  hornetq-rest.xml
 

 
  resteasy.resources
  itsvenkis.blogspot.in.rest.services.OrderSrvc
 

 
  resteasy.servlet.mapping.prefix
  /resteasy/hornetq
 

 
  org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
 

 
  org.hornetq.rest.integration.RestMessagingBootstrapListener
 

 
  resteasy
  
   org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
  
 

 
  resteasy
  /resteasy/hornetq/*
 

 
 
    BASIC
 
 
 
  
   Rest-Messaging
   /resteasy/hornetq/queues/*
   GET
   POST
   PUT
   HEAD
   DELETE
  
  
   admin
  
 


We will reuse the modified OrderSrvc.java class here. It has single method which will consume XML message and puts it in Queue using JMS API.
package itsvenkis.blogspot.in.rest.services;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.Session;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;

/**
 * @author itsvenkis
 *
 */
@Path("/postOrder")
public class OrderSrvc {
 
 private final Logger log = Logger.getLogger(OrderSrvc.class);
 /*
  * Map a JNDI connection factory name.As this service is going to be in same
  * JAVA VM as JMS use "java:/ConnectionFactory". You can find this entry in JBOSS server
  * standalone-full.xml configuration file. 
  */
 @Resource(mappedName = "java:/ConnectionFactory")
 private ConnectionFactory connectionFactory;
 
 /*
  * Map the queue. Note how the queue name is defined here. This should match the context
  * of JNDI defined which is "java" namespace followed by the entry name as given in
  * standalone-full.xml configuration file.
  */
 @Resource(mappedName = "java:/queue/restInterfaceQueue")
 private Queue orderQueue;
 
 @POST
 @Consumes(MediaType.APPLICATION_XML)
 public Response postOrder(String xmlStr) throws JMSException{
  log.debug("Started processing the order....");
  Connection con = null;
  try{
   //In real world you may want to do this only once
   con = connectionFactory.createConnection();
   Session session = con.createSession(false,
     Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(orderQueue);
   log.debug("starting HornetQ-JMS connection");
   con.start();
   log.debug("started HornetQ-JMS connection");
   //HORNETQ REST accepts only HTTP or OBJECTMESSAGE
   ObjectMessage objMsg = session.createObjectMessage();
   objMsg.setStringProperty("http_content$type",
     "application/xml");
   objMsg.setObject(xmlStr);
   producer.send(objMsg);
   log.debug("Sent message HornetQ-JMS to QUEUE");
  }catch(JMSException e){
   log.error("Failed to push order to the queue ", e);
  }finally{
   if(con != null){
    try{
     con.close();
    }catch(JMSException e){
     log.error("Unexpected error while trying to close the connection", e);
    }
   }
  }
  return Response.status(200).entity("Received XML").build();
 }

}

As we are using JEE 6 i.e. CDI in OrderSrvc.java we are required to turn it on by using a simple beans.xml under WEB-INF directory. It can be a empty XML file
beans.xml





pom.xml

 4.0.0
 in.itsvenkis.blogspot
 JMS-REST-EXAMPLES
 0.0.1-SNAPSHOT
 war
 A simple HORNETQ examples to demonstrate REST interface
 
  
  jms-rest-examples
  
   
    org.apache.maven.plugins
    maven-war-plugin
    
     
      
       org.hornetq
      
     
    
   
  
 
 
  
   jboss
   http://repository.jboss.org/maven2
  
 
 
  
   org.jboss.resteasy
   resteasy-jaxrs
   3.0.0.Final
  
  
   org.jboss.resteasy
   resteasy-jaxb-provider
   3.0.0.Final
  
  
   org.jboss.spec.javax.jms
   jboss-jms-api_1.1_spec
   1.0.1.Final
  
  
   log4j
   log4j
   1.2.17
  
  
   org.hornetq.rest
   hornetq-rest
   2.3.5.Final
  
 


project structure
dependencies

Now build and deploy the application. We are now ready to consume and produce messages using HORNETQ REST interface.
DEMO
Start your server after deploying the war file

Now post our first message to the queue named "restInterfaceQueue" using REST WS call in OrderSrvc.java. It uses regular JMS API to post the message to queue. url to post the xml message using restclient firefox plugin 'http://localhost:8080/jms-rest-examples/resteasy/hornetq/postOrder'

XML posted

Mumbai

300

f238
OR908765


The message counter for the queue should be 1 now as shown in admin console of our JBOSS server.
Now let us consume this message using REST interface. First we will do a GET request to 'http://localhost:8080/jms-rest-examples/resteasy/hornetq/queues/jms.queue.restInterfaceQueue'. To understand how this URL is formed lets break it into pieces
  •  http://localhost:8080/jms-rest-examples- your application context path
  • /resteasy/hornetq- As mapped for RESTEasy path in web.xml
  • /queues- All REST interface URLS should have queues followed by the original queue name itself which is jms.queue.restInterfaceQueue
As you may have already guessed HORNETQ will retrun us some bunch of custom headers with the GET request. Custom headers returned are shown below
Notice the msg-pull-consumer header returned. We will use that URL to create a service so that we can pull the message from the queue. To create a service do a empty post to the URL as mentioned by msg-pull-consumer header

Below are the custom headers returned from above request.

Notice the 'msg-consume-next' header value returned.Do a POST request to this URL to consume/pull the message from the queue.
below is the consumed message

This network roundtrip is just done once and to consume next message we need not issue the GET request again and start the cycle. Instead we can use 'msg-consume-next' header returned to consume next message and do the polling.If by any chance you miss the URL you can issue a get again to get url values as headers.
Now let us look at Produce an message using REST interface
Do a get request to 'http://localhost:8080/jms-rest-examples/resteasy/hornetq/postOrder' and use 'msg-create' header value and do a post

Notice the headers returned from the above POST request.'msg-create-next: http://localhost:8080/jms-rest-examples/resteasy/hornetq/queues/jms.queue.restInterfaceQueue/create'. Do a post to the URL returned as mentioned by 'msg-create-next' to create a message in the queue

This will create a new message in the queue.
This brings us to the end of the tutorial which covers how to post message and consume message using REST interface.
I was really excited to see producers and consumers via REST interface in JMS queue. If your application needs to support cross platform messaging I would strongly suggest to use REST interface.
Hope this tutorial helps you to understand REST interface. If you have any questions please do not hesitate to ask it in comments section. I will be very happy to answer them.
Dear Readers, kindly like us on facebook or follow me on Google+

Saturday, August 31, 2013

Exceptions!!!!! Hornetq Exception solved


java.lang.RuntimeException: HornetQException[errorType=NOT_CONNECTED message=HQ119007: Cannot connect to server(s). Tried with all available servers.]
One of the exception I ran into while experimenting with HORNETQ REST INTERFACE. Hope this saves your time!!!!
This is caused because of not mentioning hornetq and netty dependencies in MANIFEST.MF file. Just add "Dependencies: org.hornetq, org.jboss.netty" in MANIFEST.MF in your WAR file or in your pom.xml.

    org.apache.maven.plugins
    maven-war-plugin
    
     
      
       org.hornetq,org.jboss.netty
      
     
    
   
Exception full stack trace
15:05:57,228 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/jms-rest-examples]] (ServerService Thread Pool -- 59) JBWEB000287: Exception sending context initialized event to listener instance of class org.hornetq.rest.integration.RestMessagingBootstrapListener: java.lang.RuntimeException: HornetQException[errorType=NOT_CONNECTED message=HQ119007: Cannot connect to server(s). Tried with all available servers.]
 at org.hornetq.rest.integration.RestMessagingBootstrapListener.contextInitialized(RestMessagingBootstrapListener.java:40) [hornetq-rest-2.3.5.Final.jar:]
 at org.apache.catalina.core.StandardContext.contextListenerStart(StandardContext.java:3339) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1]
 at org.apache.catalina.core.StandardContext.start(StandardContext.java:3777) [jbossweb-7.2.0.Final-redhat-1.jar:7.2.0.Final-redhat-1]
 at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:156) [jboss-as-web-7.2.0.Final-redhat-8.jar:7.2.0.Final-redhat-8]
 at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:60) [jboss-as-web-7.2.0.Final-redhat-8.jar:7.2.0.Final-redhat-8]
 at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:93) [jboss-as-web-7.2.0.Final-redhat-8.jar:7.2.0.Final-redhat-8]
 at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [rt.jar:1.7.0_25]
 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) [rt.jar:1.7.0_25]
 at java.util.concurrent.FutureTask.run(FutureTask.java:166) [rt.jar:1.7.0_25]
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_25]
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_25]
 at java.lang.Thread.run(Thread.java:724) [rt.jar:1.7.0_25]
 at org.jboss.threads.JBossThread.run(JBossThread.java:122)
Caused by: HornetQException[errorType=NOT_CONNECTED message=HQ119007: Cannot connect to server(s). Tried with all available servers.]
 at org.hornetq.core.client.impl.ServerLocatorImpl.createSessionFactory(ServerLocatorImpl.java:863) [hornetq-core-client-2.3.5.Final.jar:]
 at org.hornetq.rest.MessageServiceManager.start(MessageServiceManager.java:157) [hornetq-rest-2.3.5.Final.jar:]
 at org.hornetq.rest.integration.RestMessagingBootstrapListener.contextInitialized(RestMessagingBootstrapListener.java:34) [hornetq-rest-2.3.5.Final.jar:]
 ... 12 more

15:05:57,290 ERROR [org.apache.catalina.core] (ServerService Thread Pool -- 59) JBWEB001103: Error detected during context /jms-rest-examples start, will stop it
15:05:57,311 ERROR [org.jboss.msc.service.fail] (ServerService Thread Pool -- 59) MSC000001: Failed to start service jboss.web.deployment.default-host./jms-rest-examples: org.jboss.msc.service.StartException in service jboss.web.deployment.default-host./jms-rest-examples: org.jboss.msc.service.StartException in anonymous service: JBAS018040: Failed to start context
 at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:96)
 at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471) [rt.jar:1.7.0_25]
 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) [rt.jar:1.7.0_25]
 at java.util.concurrent.FutureTask.run(FutureTask.java:166) [rt.jar:1.7.0_25]
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) [rt.jar:1.7.0_25]
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) [rt.jar:1.7.0_25]
 at java.lang.Thread.run(Thread.java:724) [rt.jar:1.7.0_25]
 at org.jboss.threads.JBossThread.run(JBossThread.java:122) [jboss-threads-2.1.0.Final-redhat-1.jar:2.1.0.Final-redhat-1]
Caused by: org.jboss.msc.service.StartException in anonymous service: JBAS018040: Failed to start context
 at org.jboss.as.web.deployment.WebDeploymentService.doStart(WebDeploymentService.java:161)
 at org.jboss.as.web.deployment.WebDeploymentService.access$000(WebDeploymentService.java:60)
 at org.jboss.as.web.deployment.WebDeploymentService$1.run(WebDeploymentService.java:93)
 ... 7 more

Tuesday, August 27, 2013

Simple HornetQ JMS Tutorial


If you are interested to see the other REST tutorials I already blogged, please find them below
As part of series of REST tutorials, I am blogging this simple HorneQ JMS tutorial. HornetQ is the default meessaging system in JBOSS application server.
A detailed documentation about HornetQ is available @ here.Lets get started with the tutorial
Technologies used
  • HornetQ
  • JBOSS eap 6.1
  • JAVA 7
  • RESTEasy
  • CDI
  • Maven
 Now lets see what configuration we require before we start our coding. Before we start any configuration a basic understanding of JBOSS server is required. JBOSS server directory structure will look this

Different startup configurations are available in JBOSS server. To have the HORNETQ integrated and started with JBOSS AS one should use standalone-full.xml. For example we will start the server using this command
./standalone.sh --server-config=standalone-full.xml.
We will add the queues needed for our tutorial in standalone-full.xml. There are other ways too to declare the queues/topics which is out of scope of this post. I am gonna develop a order processing system which can receive a order which is a XML file and it will put the order in a queue which will be consumed by other consumers. Lets name that queue as "ticketOrderQueue". Here is how we declare in standalone-full.xml
                 
                    
                        
                        
                    
                    
                        
                        
                    
                
To connect to this queues we will use JNDI connection factories. By default JBOSS gives us couple of connection factories like "InvmConnectionFactory" and "RemoteConnectionFactory" which will use netty connector. Code snippet of these factories is below

                        
                            
                        
                        
                            
                        
                    
                    
                        
                            
                        
                        
                            
                        
                    

If our message producer or consumer is in same JAVA VM as HornetQ one should use "java:/ConnectionFactory" and if it is remote client consuming or producing messaging to JMS destinations one should use "RemoteConnectionFactory". Noteworthy about the contexts they use as shown in above snippet. For example, "RemoteConenctionFactory" uses "java:jboss/exported" context. Once this is done, we will define users for JBOSS application server as administrator and for HORNETQ. Use add-user utility to add application users. Note: I am using UBUNTU as my dev env. However for windows it should be the same process with bat files First let us add admin user. Please find the details in below screenshot

Now let us add some application users for HORNETQ. Please find the details below

Now start the server and we will add some security to our HORNETQ. start server

type in and enter the credentials you configured for admin as mentioned above and select JMS destination from left hand menu. You should now be able to see this view with the queues which we defined

To add some security to our HORNETQ lets go to profile view by clicking on profile link on top right side on admin view and select Messaging/destination/view and select security settings and add the role permissions as shown below

This should bring us to end of configuration section. Now lets start coding our producer which is a RESTFUL web service and receives a XML order and pushes it to a queue. OrderSrvc.java
package itsvenkis.blogspot.in.rest.services;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.log4j.Logger;

/**
 * @author itsvenkis
 *
 */
@Path("/postOrder")
public class OrderSrvc {
 
 private final Logger log = Logger.getLogger(OrderSrvc.class);
 /*
  * Map a JNDI connection factory name.As this service is going to be in same
  * JAVA VM as JMS use "java:/ConnectionFactory". You can find this entry in JBOSS server
  * standalone-full.xml configuration file. 
  */
 @Resource(mappedName = "java:/ConnectionFactory")
 private ConnectionFactory connectionFactory;
 
 /*
  * Map the queue. Note how the queue name is defined here. This should match the context
  * of JNDI defined which is "java" namespace followed by the entry name as given in
  * standalone-full.xml configuration file.
  */
 @Resource(mappedName = "java:/queue/ticketOrderQueue")
 private Queue orderQueue;
 
 @POST
 @Consumes(MediaType.APPLICATION_XML)
 public Response postOrder(String xmlStr) throws JMSException{
  log.debug("Started processing the order....");
  Connection con = null;
  try{
   //In real world you may want to do this only once
   con = connectionFactory.createConnection();
   Session session = con.createSession(false,
     Session.AUTO_ACKNOWLEDGE);
   MessageProducer producer = session.createProducer(orderQueue);
   log.debug("starting HornetQ-JMS connection");
   con.start();
   log.debug("started HornetQ-JMS connection");
   TextMessage txtMsg = session.createTextMessage();
   txtMsg.setText(xmlStr);
   producer.send(txtMsg);
   log.debug("Sent message HornetQ-JMS to QUEUE");
  }catch(JMSException e){
   log.error("Failed to push order to the queue ", e);
  }finally{
   if(con != null){
    try{
     con.close();
    }catch(JMSException e){
     log.error("Unexpected error while trying to close the connection", e);
    }
   }
  }
  return Response.status(200).entity("Received XML").build();
 }

}

In the above web service I used @Resource annotation which is nothing but through CDI. Inorder to make CDI work one should have a beans.xml defined under WEB-INF folder. This xml will tell JBOSS to enable CDI.Noteworthy that this xml can be empty. I will add tutorials specific to CDI in the near future. For now,please find the xml below





web.xml

 
  resteasy.resources
  itsvenkis.blogspot.in.rest.services.OrderSrvc
 
 
  resteasy.servlet.mapping.prefix
  /resteasy
 
 
  
   org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
 
 
  resteasy
  
   org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
 
 
  resteasy
  /resteasy/*
 


pom.xml

  4.0.0
  in.itsvenkis.blogspot
  JMS-flight-booking
  0.0.1-SNAPSHOT
  war
  
  jms-flight-booking
  
  Simple application to understand RESTEasy,Hornet Q
  
   
      jboss
      http://repository.jboss.org/maven2
   
   
   
   
    org.jboss.resteasy
    resteasy-jaxrs
    3.0.0.Final
   
   
 org.jboss.resteasy
 resteasy-jaxb-provider
 3.0.0.Final
 
 
 org.jboss.spec.javax.jms
 jboss-jms-api_1.1_spec
 1.0.1.Final
 
 
 log4j
 log4j
 1.2.17
 
  


Now build,deploy and start your server. We will restful mozilla plugin to post XML file to our URL

To check if the message has reached our "ticketOrderQueue" go to admin view in the JBOSS server and goto JMS view. You should be able to see messages in queue count as one

Now lets code a simple consumer class which will have a main method
package itsvenkis.blogspot.in.example.consumer;

import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;

public class JMSConsumerExample {
 /*
  * for a remote client use RemoteConnectionFactory JNDI which will be defined in standalone-full.xml
  * configuration file
  */
 private static final String DEFAULT_CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
 //Queue name as mentioned in standalone-full.xml under 
 private static final String DEFAULT_DESTINATION = "jms/queue/ticketOrderQueue";
 private static final String DEFAULT_USERNAME = "jmsadmin";
 private static final String DEFAULT_PASSWORD = "*****";
 private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
 private static final String PROVIDER_URL = "remote://localhost:4447";

 public static void main(String[] args) throws Exception {
  ConnectionFactory connectionFactory = null;
  Connection connection = null;
  Session session = null;
  MessageConsumer consumer = null;
  Destination destination = null;
  TextMessage message = null;
  Context context = null;
  try {
   final Properties env = new Properties();
   env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
   env.put(Context.PROVIDER_URL,
     System.getProperty(Context.PROVIDER_URL, PROVIDER_URL));
   env.put(Context.SECURITY_PRINCIPAL,
     System.getProperty("username", DEFAULT_USERNAME));
   env.put(Context.SECURITY_CREDENTIALS,
     System.getProperty("password", DEFAULT_PASSWORD));
   context = new InitialContext(env);
   String connectionFactoryString = System.getProperty(
     "connection.factory", DEFAULT_CONNECTION_FACTORY);
   connectionFactory = (ConnectionFactory) context
     .lookup(connectionFactoryString);
   String destinationString = System.getProperty("destination",
     DEFAULT_DESTINATION);
   destination = (Destination) context.lookup(destinationString);
   connection = connectionFactory.createConnection(
     System.getProperty("username", DEFAULT_USERNAME),
     System.getProperty("password", DEFAULT_PASSWORD));
   session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
   consumer = session.createConsumer(destination);
   connection.start();
   message = (TextMessage) consumer.receive(10000);
   System.out.println("Received message " + message.getText());
  } catch (Exception e) {
   System.out.println(e.getMessage());
   throw e;
  } finally {
   if (context != null) {
    context.close();
   }
   if (connection != null) {
    connection.close();
   }
  }
 }
}

Run the application and you should be able to see this output now

Project directory structure

Project dependencies
This brings us to the end of this tutorial!!!!
Dear Readers, kindly like us on facebook

Friday, August 23, 2013

RESTEasy XML marshalling and unmarshalling examples


Many enterprise applications use Marshalling and unmarshalling i.e. XML to POJO and POJO to XML. This tutorial will try show how to do Marshalling and unmarshalling using JAXB and RESTEasy.
Technologies used
  1. JAVA
  2. RESTEasy
  3. JAXB
  4. JBOSS eap 6.1
  5. Maven
As an example let us try to convert XML to Java object and Java object to XML. This is how our simple order.xml looks like
 

Mumbai

300

f238
OR908765


Now let us declare our domain objects to represent this XML
order.java
 
package itsvenkis.blogspot.in.domain;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

/**
 * @author itsvenkis
 *
 */
@XmlRootElement(name ="order")
public class Order {
 
 private String flightNumber;
 private String orderId;
 private String source;
 private String destination;
 private Flight flight;
 
 public Flight getFlight() {
  return flight;
 }
 
 @XmlElement
 public void setFlight(Flight flight) {
  this.flight = flight;
 }

 public String getFlightNumber() {
  return flightNumber;
 }
 
 @XmlElement
 public void setFlightNumber(String flightNumber) {
  this.flightNumber = flightNumber;
 }
 public String getOrderId() {
  return orderId;
 }
 @XmlElement
 public void setOrderId(String orderId) {
  this.orderId = orderId;
 }
 public String getSource() {
  return source;
 }
 @XmlElement
 public void setSource(String source) {
  this.source = source;
 }
 public String getDestination() {
  return destination;
 }
 @XmlElement
 public void setDestination(String destination) {
  this.destination = destination;
 }
}
Flight.java
package itsvenkis.blogspot.in.domain;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;

/**
 * @author itsvenkis
 *
 */
public class Flight {
 
 private String flightMaker;
 private String flightType;
 private int flightAge;
 
 public int getFlightAge() {
  return flightAge;
 }
 
 @XmlElement
 public void setFlightAge(int flightAge) {
  this.flightAge = flightAge;
 }
 @XmlAttribute
 public String getFlightMaker() {
  return flightMaker;
 }
 public void setFlightMaker(String flightMaker) {
  this.flightMaker = flightMaker;
 }
 
 @XmlAttribute
 public String getFlightType() {
  return flightType;
 }
 public void setFlightType(String flightType) {
  this.flightType = flightType;
 }
}

Now this is how our RESTEasy service class will look like OrderSrvc.java
package itsvenkis.blogspot.in.rest.services;

import itsvenkis.blogspot.in.domain.Flight;
import itsvenkis.blogspot.in.domain.Order;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/getOrder")
public class OrderSrvc {
 
 @GET
 @Produces("application/xml")
 public Order getOrder(){
  Order order = new Order();
  order.setDestination("Mumbai");
  order.setFlightNumber("f238");
  order.setOrderId("OR908765");
  Flight flight = new Flight();
  flight.setFlightMaker("BOEING");
  flight.setFlightType("COMMERCIAL");
  flight.setFlightAge(300);
  order.setFlight(flight);
  return order;
 }
 
 @POST
 @Consumes(MediaType.APPLICATION_XML)
 public Response postOrder(Order order){
                //Its crime to use System.out.println . Use loggers instead
  System.out.println(order.getDestination());
  return Response.status(200).entity("Received XML").build();
 }

}
Now lets go ahead and define our web.xml and pom.xml
web.xml

 
  resteasy.resources
  itsvenkis.blogspot.in.rest.services.OrderSrvc
 
 
  resteasy.servlet.mapping.prefix
  /resteasy
 
 
  
   org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
 
 
  resteasy
  
   org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
 
 
  resteasy
  /resteasy/*
 


pom.xml

  4.0.0
  in.itsvenkis.blogspot
  flight-booking
  0.0.1-SNAPSHOT
  war
  JBOSS-EXAMPLES
  Simple application to understand RESTEasy,Hornet Q
  
   
      jboss
      http://repository.jboss.org/maven2
   
   
   
   flightbooking
   
   
   
    org.jboss.resteasy
    resteasy-jaxrs
    3.0.0.Final
   
   
 org.jboss.resteasy
 resteasy-jaxb-provider
 3.0.0.Final
 
  


Now biuld, deploy and start the server

After starting the server, try this URL

Now lets try to convert XML to Java object. I used REST client firefox plugin to post XML. Do remember to add request header for content type before posting XML

This brings us to the end of the tutorial. I will post more examples on RestEasy, HornetQ, and JBOSS in the future. If you want any specific tutorial let me know in the comments section.
Dear Readers, kindly like us on facebook to see whats happening on this blog

Friday, August 16, 2013

RESTful WEB SERVICES and RESTFul JAVA with RESTEasy


A simple RESTEasy Helloworld example
Technologies used
  1. Maven
  2. JBOSS AS
  3. RESTEasy
First let us take a look at the pom.xml

  4.0.0
  in.itsvenkis.blogspot
  resteasy-examples
  0.0.1-SNAPSHOT
  war
  jboss-resteasy
  Rest easy tutorials
  
  resteasyTutorials
  
  
   
      jboss
      http://repository.jboss.org/maven2
   
  
      
          org.jboss.resteasy
          resteasy-jaxrs
          3.0.0.Final

web.xml
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
          http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    
        resteasy.resources
        itsvenkis.blogspot.in.resteasy.examples.HelloWorldService
    
    
        resteasy.servlet.mapping.prefix
        /resteasy
    
    
        
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
    
    
        resteasy
        
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
    
    
        resteasy
        /resteasy/*
    
Service class
package itsvenkis.blogspot.in.resteasy.examples;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/helloworld")
public class HelloWorldService {

    @GET
    @Path("/{param}")
    public Response greetUser(@PathParam("param") String name) {
        return Response.status(200).entity("Hello World " + name).build();
    }
}
 
Now build and deploy the war file and start your server and try this url http://localhost:8080/resteasyTutorials/resteasy/helloworld/nandu
I will post more tutorials on RESTEasy, Hornet Q, JBOSS,CDI..... in the future
Dear Readers, kindly like us on facebook to see whats happening on this blog