Saturday, 9 August 2014

Web Service Tutorial Series: SOAP and REST

This tutorial series will teach you the basic concepts of web services using different SOAP engines like Apache AXIS2, Apache CXF ,JAX-WS and Jersey.

 It also provides a solution for sending large attachment with SOAP messages by using MTOM (SOAP Message Transmission Optimization Mechanism) which encodes binary data in base64Binary and sends the data as binary attachment rather than keeping it with actual SOAP message. 


This series also shows that by simply making method calls using the SAAJ API, you can read and write SOAP-based XML messages, and you can optionally send and receive such messages over the Internet.


This series will also show developers to build  applications that use database driven web services with persistence framework like Hibernate and then consuming Restful web service in cloud to be invoked by Android and J2ME Client.

You will also learn to develop restful service that will produce the output in diffrent format(json, xml etc) based on the client request. It will also guide you to develop web-service security with Apache CXF. 


Lets get started..!!



1. Developing a web service and consuming it with J2ME Client

This tutorial demonstrates how to develop web service with Java 2 Platform and deploying it in WebSphere Application Server Community Edition (WASCE) and Tomcat server using two simple examples (Hello World and Logging) and invoking them through a J2ME client. Eclipse IDE is also used to develop a web service and deploy it in the WASCE. There is also a Stock-Quote service example in a remote location (not in local host) developed in .NET platform and this tutorial will show how to invoke it using a J2ME client.

Objectives
In this tutorial, learn how to:
  1. Download and Install the web servers (Tomcat and WASCE), if it is not already installed, and make minor additions to it to successfully implement the given examples.
  2. Download and install Sun J2ME Emulator (Java[TM] ME Platform SDK 3.0) for developing J2me Client to invoke the web services.
  3. Download and install Axis2 runtime environment into Tomcat for developing and deploying Web service (Hello World).
  4. Developing web service (Logging) using Eclipse IDE and deploying it in WebSphere Community edition (WASCE).
  5. Accessing Remote web service (Stock Quote) developed in .Net platform and hosted in the Remote machine through J2me client.


  2. Developing the code and contract first approach web service with Axis2


This Tutorial series will describes the way of developing web service with different Web Service Engine like (Axis2,JAX-WS and CXF). Web services can be implemented using different application protocols like SOAP, XML, JSON, RESTful HTTP, and support various transport protocols like HTTP or JMS (Java Message Service). In order to create a Web service, you will need some tools. At a minimum, you will need some type of SOAP processing engine to parse the messages that are received and to call the functions or methods that the message indicates. Many products are on the market that provides this processing. The goal of every Web services development tool is to build a bridge between the SOAP processor and the business logic that is running on the server. Normally, this business logic is kept separate from the SOAP processing logic. 
You will learn how to develop a Credit Card Validation web service with Code first (Bottom up) approach and followed by Product Catalog web service development with Contract First(Top Down) Approach using Axis2.

Objectives
In this tutorial, you will learn how to:
  1. Download and install the web servers (Tomcat), if it is not already installed, and make minor additions to it to successfully implement the given examples.
  2. Download and install Axis2 engine to generate the Stubs as well as Service skeleton.
  3. Download and install Axis2 runtime environment into Tomcat for developing and deploying web service (Credit Card Validation and Product Catalog).
  4. Developing POJO Client for the web service (Credit Card Validation) using Eclipse IDE.



3. File download web service with JAX-WS

This tutorial will show how to develop a simple Hello User web service with JAX-WS and followed by a File Download web service,where client can download file from web service and store in clients location. Finally a SAAJ client will be developed to access the Product Catalog web service developed in Part 1 using Axis2 with Contract First approach. JAX-WS replaces the older JAX-RPC API. Unlike SAAJ, JAX-WS does not require you to know very much about XML or WSDL. The entire XML layer is hidden from developers, who can instead just work with objects generated by web services tools that come with Java SE 6 and EE 5.

Objectives
In this tutorial, you will learn how to:
  1. Develop Hello User and File Download web service and their clients using JAX-WS library in Eclipse IDE.
  2. Develop SAAJ client to send request and receive response from Product Catalog web service using Eclipse IDE.



4. File uploading web service with Apache CFX

This tutorial demonstrates how to develop web service that can upload a file from client machine to the server. The client application submits a file location and invokes the web service which receives the file byte by byte and stores in a fixed specified location.



Objectives
In this tutorial, you will learn how to:

  1. Build a web service using CXF and deploy it in the tomcat server.
  2. Learn how to send large binary attachments using the MTOM standard.
Continue Reading >>


5.  Develop Database driven Web service in Cloud(GAE) and consuming with Android/J2ME clients

This Tutorial will describes the way of developing web service (JAX-WS and REST). Web services can be implemented using different application protocols like SOAP, XML, JSON, Restful HTTP, and support various transport protocols like HTTP or JMS (Java Message Service). This tutorial will help you in developing a Database Driven Information Retrieval Web service with Hibernate, followed by Hello User Restful web service which is deployed in the Google Cloud (GAE). Finally consuming the developed web services with mobile clients (J2ME and Android).

Objectives
In this tutorial, learn how to:

  1. Develop and deploy a JAX-WS Web Service, which operates on DB2 database using Hibernate as an ORM framework.
  2. Develop a simple Restful webservice and deploy it in Cloud (GAE).
  3. Invoke both the above Web Services using an Android Client and a J2ME client.

Continue Reading >>



Restful service  series with Jersey

In this tutorial series you will learn the following:

6.  File Upload and Download Service using Jersey : In this tutorial you will learn how to create File Upload and Download restful Web service
service using jersey.
Continue Reading >>

7.  Conditional Get and Http Caching using Jersey : In this tutorial you will learn the conditional http feature using Jersey.The HTTP Protocol defines a caching mechanism, in which the proxy web-servers can cache pages, files, images etc. Since caching is in place, There is a method which the servers are asked to return the document, either the “cached” or “live” document. Continue Reading >>

8. Jersey (JAX-RS) with Protocol Buffer for high performance Rest API : In this tutorial you will learn how to develop a Restful service with Jersey/JAX-RS using protocol buffer (commonly known as protobuf)for high performance.One of the great things about the JAX-RS specification is that it is very extensible and adding new providers for different mime-types is very easy. One of the interesting binary protocols out there is Google Protocol Buffers. Continue Reading >>

9. Dynamic Content Mapping with Jersey : In this article you will learn how to do return the response dynamically based on header or client request, something called Dynamic Content Mapping,much like Spring's ContentNegotiatingViewResolver.Continue Reading >>





Sunday, 3 August 2014

ActiveMQ vs RabbitMQ vs ZeroMQ vs Apache Qpid vs Kafka vs IronMQ -Message Queue Comparision

What are Message Queues[MQ]?

Message Oriented Middleware or MOM concept involves the exchange of data between different applications using messages asynchronously. Using this mechanism, applications are decoupled and senders and receivers exist without the knowledge of each other. It becomes the responsibility of the messaging system (Message Oriented Middleware) to transfer the messages between applications. Queues allow you to store metadata for processing jobs at a later
date. They can aid in the development of SOA (service-oriented architecture) by providing the flexibility to defer tasks to separate processes. When applied correctly, queues can dramatically increase the user experience of a web site by reducing load times.



Advantages of message queues:
•Asynchronous: Queue it now, run it later.
•Decoupling: Separates application logic.
•Resilience: Won't take down your whole application if part of it fails.
•Redundancy: Can retry jobs if they fail.
•Guarantees: Makes sure that jobs will be processed.
•Scalable: Many workers can process individual jobs in a queue.



Use cases of message queues:
•Sending/receiving data from a third-party APIs
•Communication between various application asynchronously
•Sending an e-mail, Uploading documents
•Running labour intensive processes

JMS vs AMQP
AMQP is an application-level standard for Message Oriented Middleware (MOM). JMS is a standard API for Java for communicating with MOM.
Two different Java applications using JMS could be using different MOM and hence still be unable to communicate. ActiveMQ is a MOM system with a JMS library that allows Java programs to access it using JMS, but it can't necessarily communicate with another JMS Java program using, say, WebLogic MOM.
Different AMQP MOM systems can interoperate with each other (assuming that they are using the same version of AMQP) since AMQP is a standard along the same lines as, say SMTP. There is no reason that an AMQP MOM system could not also provide a JMS library for its Java clients.


OpenSource Message Queue

1. RabbitMQ is one of the leading implementation of the AMQP protocol (along with ApacheQpid). Therefore, it implements a broker architecture, meaning that messages are queued on a central node before being sent to clients. This approach makes RabbitMQ very easy to use and deploy, because advanced scenarios like routing, load balancing or persistent message queuing,Negetive Ackowledgement(NACK), Requeing and Delay or Schedule messaging are supported in just a few lines of code. However, it also makes it less scalable and “slower” because the central node adds latency and message envelopes are quite big.

2. Apache ActiveMQ is the most popular and powerful open source messaging and Integration Patterns server.Supports many advanced featuressuch as Message Groups, Virtual Destinations, Wildcards and Composite Destinations.It makes for a reliable hub in any message-oriented enterprise application and integrates beautifully with Java EE containers,ESBs, and other JMS providers
ActiveMQ Apollo is a faster, more reliable, easier to maintain messaging broker built from the foundations of the original ActiveMQ- a new Gen ActiveMQ. It accomplishes this using a radically different threading and message dispatching architecture. Like ActiveMQ, Apollo is a multi-protocol broker and supports STOMP, AMQP, MQTT, Openwire, SSL, and WebSockets.

3. ZeroMQ is a very lightweight messaging system specially designed for high throughput/low latency scenarios like the one you can find in the financial world. Zmq supports many advanced messaging scenarios but contrary to ActiveMQ/RabbitMQ, you’ll have to implement most of them yourself by combining various pieces of the framework (e.g : sockets and devices).ZeroMQ is a lightweight message orientated socket implementation. It is also suitable
for in-process asynchronous programming. It is possible to run a "Enterprise Messaging System" over ZeroMQ, but you would have to implement a lot on your own.

4. Kafka is a high throughput distributed messaging system.Written and used by LinkedIn to offload processing of all page and other views .Defaults to using persistence, uses OS disk cache for hot data (has higher throughput then any of the above having persistence enabled).Supports both on-line as off-line processing.Kafka does work on the push - pull basic and capable of handling large scale real time streams.

5. Apache Qpid, an open-source messaging system, implements the Advanced Message Queuing Protocol. It provides transaction management, queuing, distribution, security,management, clustering, federation and heterogeneous multi-platform support.

6. IronMQ is an easy-to-use highly available message queuing service. It is available as a cloud service on Amazon and Rackspace as well as on-premise with Iron.io's enterprise offering.Features include a nice dashboard to manage queues, easy to create webhooks, unicast and multicast Push Queues, autoscaling alerts for worker processes, and error queues.An easy-to-
use highly available message queuing service. Built for distributed cloud applications with critical messaging needs. Provides on-demand message queuing with HTTPS transport, one-time FIFO delivery, message persistence,and cloud-optimized performance.


Message Queue Comparison



BenchMark / Performance

• ActiveMQ (https://activemq.apache.org/benchmark-tests.html)

• Apollo (http://activemq.apache.org/apollo/documentation/performance-scaling.html)


• RabbitMQ (http://www.rabbitmq.com/blog/)


• ZeroMQ (http://zeromq.org/results:ib-tests-v206)


• Apache Qpid (http://qpid.apache.org/releases/qpid-0.20/)


• Kafka (https://kafka.apache.org/07/performance.html)


Conclusion
ActiveMQ or Apollo is simply the leader when it comes to ease of configariton and different persistentstore, at the cost of performance in persistence mode.ApacheMQ and Apache Qpid seems to bevery good among broker based MQ at performing without persistence.Apollo is better in terms of performance and reliability than ActiveMQ /Apache Qpid.

•Just like other brokers based MQ, RabbitMQ is is best sutable for advance messaging pattren having routing,load balancing.However, it also makes it less scalable and “slower” because the central node adds latency and message envelopes are quite big. However even in persistent mode RabbitMQ performs better than ActiveMQ or Apache Qpid.

• ZeroMQ broker outperforms all others for simple messaging pattern between application. This means that unless you have a need for complex broker features,ZeroMQ is a perfect message dispatcher among processes.If you want one application to send messages to another as quickly as possible, you need ZeroMQ.Its crazy fast for transient message.

•Kafka does work on the push - pull basic and capable of handling large scale real time streams.It also provide ordered message delivery.Kafka's performance is effectively constant with respect to data size so retaining lots of data will not be a problem.Kafka is ideal if you are looking for reliable distributed messaging system with good throughput.Kafka is used at LinkedIn and it handles over 10
billion message writes per day with a sustained load that averages 172,000 messages per second.

•IronMQ is good in case of distributed cloud based queueing.It integrates with application running in Amazon or Rackspace,but its commercial.

Related Article:

  1. Real World  Example of RabbitMQ
  2. Delay or Scheduled Message with RabbitMQ


Spring Security with Google, Open-id and LDAP

In this tutorial you will Learn how to integrate Spring security with Gmail, OpenId or Ldap based authentication.

Technologies used :
  1. Spring 3.2.8.RELEASE
  2. Spring Security 3.2.3.RELEASE
  3. JDK 1.7
  4. Maven 3
  5. OpenLDap or Apache DS
For using this tutorial it is assumed that the user alraedy have Google account ,OpenId account and set up LDAP (using Open-LDAP or Apache DS).

Directory Structure

Spring Security Configuration
Defined your custom login form in Spring XML file. See explanation below :
  1. login-page=”/login” – The page to display the custom login form
  2. authentication-failure-url=”/login?error” – If authentication failed, forward to page /login?error
  3. logout-success-url=”/login?logout” – If logout successful, forward to view /logout
  4. username-parameter=”username” – The name of the request which contains the “username”. In HTML, this is the name of the input text.
  5. <csrf/> – Enable the Cross Site Request Forgery (CSRF) protection,, by default, CSRF protection is disabled.Also you need to add _csrf.token in login.jsp form.
Normally, we don’t involve in the authentication like login or logout processing, let Spring handle it, we just handle the successful or failed page to display.
<http auto-config="true">
<intercept-url pattern="/admin**" access="ROLE_USER" />
<form-login 
    login-page="/login" 
    default-target-url="/welcome" 
    authentication-failure-url="/login?error" 
username-parameter="username"
password-parameter="password" />
<logout logout-success-url="/login?logout"  />
<!--OpenId Login-->
<openid-login />
<!-- enable csrf protection -->
<csrf/>
</http>
<!-- For Google Based Authentication -->
<authentication-manager>
<authentication-provider>
<user-service>
<user name="https://www.google.com/accounts/o8/id?id=AItOawnvPl3Y3exYxxvh8B4b19fPKmFn7dTkxn4" password="" authorities="ROLE_USER,ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager>

<!-- For OpenID (MYOpenId) Based Authentication
<authentication-manager>
<authentication-provider>
<user-service>
<user name="http://kuntal29.myopenid.com/" password="" authorities="ROLE_USER, ROLE_ADMIN" />
</user-service>
</authentication-provider>
</authentication-manager> -->

<!-- For Basic Hardcoded Authentication
<authentication-manager>
<authentication-provider>
<user-service>
<user name="kuntal" password="ganguly" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>-->

<!-- For Basic LDAP(Open Ldap) based Authentication
<ldap-server url="ldap://kuntal.example.org:389/dc=kuntal,dc=example,dc=org"/>
<authentication-manager>
<ldap-authentication-provider  
   user-search-filter="(uid={0})" user-search-base="ou=groups"
        role-prefix="ROLE_USER">
</ldap-authentication-provider>
</authentication-manager>-->

Spring MVC Controller

A simple controller.
HelloController.java

@Controller
public class HelloController {
@RequestMapping(value = { "/", "/welcome**" }, method = RequestMethod.GET)
public ModelAndView welcomePage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security");
model.addObject("message", "This is a welcome page!");
model.setViewName("hello");
return model;
}
@RequestMapping(value = "/admin**", method = RequestMethod.GET)
public ModelAndView adminPage() {
ModelAndView model = new ModelAndView();
model.addObject("title", "Spring Security Login Form");
model.addObject("message", "This is protected page for Admin Only!");
model.setViewName("admin");
return model;
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView login(@RequestParam(value = "error", required = false) String error,
@RequestParam(value = "logout", required = false) String logout) {
ModelAndView model = new ModelAndView();
if (error != null) {
model.addObject("error", "Invalid username and password!");
}
if (logout != null) {
model.addObject("msg", "You've been logged out successfully.");
}
model.setViewName("login");
return model;
}

Login Form


<html>
<head>
<title>Login Page</title>
<style>
table,th,td
{
border:1px solid black;
}
</style>
</head>
<body onload='document.loginForm.username.focus();'>

<h1>Spring Security Login Form</h1>

<div id="login-box">

<h3>Login with Username and Password</h3>

<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>


<!-- For Basic or LDAP based authentication use action url value = /j_spring_security_check . And for
     For openId based authentication use action url value = /j_spring_openid_security_check -->

<form name='loginForm'
action="<c:url value='/j_spring_openid_security_check' />" method='POST'>

<!-- Basic or LDAP based authentication with username & password-->
<table bgcolor="#00FF00">
<tr>
<td>Username:</td>
<td><input type='text' name='username'></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='password'/></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit" value="Login" /></td>
</tr>
</table><br>

<!-- Google/Gmail based authentication -->
<table bgcolor="#00AD00">
<tr>
<td>Google Login:</td>
<td><input type='hidden' name='openid_identifier' value='https://www.google.com/accounts/o8/id'></td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"value="Login" />
</td>
</tr>
</table>
<br>

<!-- MyOpenId based authentication -->
<table bgcolor="#00CF00">
<tr>
<td>OpenID Login:</td>
<td><input type='hidden' name='openid_identifier' value='http://kuntal29.myopenid.com/'>
</td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit" value="Login" />
</td>
</tr>
</table>

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

</form>
</div>
</body>
</html>

Note: For open authentication as shown in this tutorial,spring internally uses openid4java.

Demo

Welcome Page:  http://localhost:8080/spring-security/welcome


Now try to access admin page /admin:  http://localhost:8080/spring-security/admin
It will redirect to log in page as shown



Now if you select Google log in,it will take you to the Google authentication page:



On successful authentication you will be see admin page:


Download the tutorial codebase

Saturday, 26 July 2014

Publish Consume Blob and Stream Message with JMS ActiveMQ

Few months back,i was scratching my head and i was Google-ing all day for publishing and consuming Blob data(like pdf,word,excel) through message queue. Couldn't find any solution other than some tips and special url for blob messages. So i'm writing this tutorial for publish and consume Blob & Stream messages through Message Queue.I will be using ActiveMQ for this tutorial.
Note: ActiveMQ support BlobMessage .Its specific to ActiveMQ, JMS don't have any BlobMessage wrapper,it support StreamMessage.

 Producer:

import java.io.File;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.BlobMessage;

public class BlobMessageProducer {
private Connection connection = null;
private ActiveMQSession session = null;
private Destination destination = null;
private MessageProducer producer = null;
private File file;

  private void init(String fileName) throws Exception {
file = new File(fileName);
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616?jms.blobTransferPolicy.defaultUploadUrl=http://localhost:8161/fileserver/");
connection = connectionFactory.createConnection();
session = (ActiveMQSession) connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("File.Transport");
producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
connection.start();
}

public void sendFile(String fileName) {
try {
 System.out.println("Send File Start >>");
init(fileName);
BlobMessage blobMessage = session.createBlobMessage(file);
blobMessage.setStringProperty("FILE.NAME", file.getName());
blobMessage.setLongProperty("FILE.SIZE", file.length());
producer.send(blobMessage);
  System.out.println("Send File End>>");
} catch (Exception e) {

} finally {
close();
}
}

private void close() {

try {
if (connection != null) {
connection.close();
}
logger.info("--producer close end--");
} catch (JMSException e) {

}
System.exit(0);
}

public static void main(String argv[]) {
String fileName = "/home/kuntal/practice/config-data/test.pdf";
new BlobMessageProducer().sendFile(fileName);
}

}



Consumer:

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.Session;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.BlobMessage;

public class BlobMessageConsumer {
private MessageConsumer consumer;
private Connection connection = null;
private Session session = null;
private Destination destination = null;
private static Logger logger = Logger.getLogger(BlobMessageConsumer.class);
private BufferedOutputStream bos;

private void init() throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
connection = connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("File.Transport");
consumer = session.createConsumer(destination);
}

public void receiveFile(String targetFilePath) {
try {
init();
while (true) {
Message message = consumer.receive(5000);
if (message == null) {
break;
}

if (message instanceof BlobMessage) {
byte[] buffer = new byte[2048];
int length = 0;
BlobMessage blobMessage = (BlobMessage) message;
String fileName = blobMessage
.getStringProperty("FILE.NAME");

File file = new File(targetFilePath + File.separator
+ fileName);
OutputStream os = new FileOutputStream(file);
bos = new BufferedOutputStream(os);

InputStream inputStream = blobMessage.getInputStream();
while ((length = inputStream.read(buffer)) > 0) {
bos.write(buffer, 0, length);
}
}
}
} catch (Exception e) {

} finally {
close();
}
}

private void close() {

try {
if (bos != null) {
bos.close();
}
if (connection != null) {
connection.close();
}

} catch (IOException e) {

} catch (JMSException e) {

}
System.exit(0);
}

public static void main(String[] args) {
String targetFileFolder = "/home/kuntal/practice/config-data/output";
new BlobMessageConsumer().receiveFile(targetFileFolder);
}
}

For Streaming Data , JMS provides StreamMessage,which is very handy to push and pull streaming data like (log,text file) in the Message Queue.So this is how to publish and consume streaming data into ActiveMQ.

Producer:
public class StreamProducer {
private Connection connection;
private Session session;
private Destination destination;
private MessageProducer producer;
private InputStream in;

private static Logger logger = Logger.getLogger(StreamProducer.class);

public void sendFile(String fileName) {
logger.info("--sendFile start--");
try {
init(fileName);
byte[] buffer = new byte[1024];
int c = -1;
while ((c = in.read(buffer)) > 0) {
StreamMessage smsg = session.createStreamMessage();
smsg.writeBytes(buffer, 0, c);
producer.send(smsg);
logger.info("send: " + c);
}
logger.info("--sendFile end--");
} catch (Exception e) {
logger.error("--sendFile fail--", e);
} finally {
close();
}
}

private void init(String fileName) throws Exception {
File file = new File(fileName);
in = new FileInputStream(file);
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
connection = factory.createConnection();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("queue1");
producer = session.createProducer(destination);
// producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
connection.start();
}

private void close() {
logger.info("--producer close start--");
try {
if (in != null) {
in.close();
}
if (connection != null) {
connection.close();
}
logger.info("--producer close end--");
} catch (IOException e) {
logger.error("--close InputStream fail--", e);
} catch (JMSException e) {
logger.error("--close connection fail--", e);
}
System.exit(0);
}

public static void main(String argv[]) {
ClassLoader loader = StreamProducer.class.getClassLoader();
//URL url = loader.getResource("test.txt");
String fileName = "/home/kuntal/practice/config-data/test.txt";
new StreamProducer().sendFile(fileName);
}

}

Consumer:
public class StreamConsumer {
private MessageConsumer consumer;
private Connection connection = null;
private Session session = null;
private Destination destination = null;
private static Logger logger = Logger.getLogger(StreamConsumer.class);
private BufferedOutputStream bos = null;

private void init(String targetFileName) throws Exception {
logger.info("--init start--");
logger.info("--targetFileName--" + targetFileName);
OutputStream out = new FileOutputStream(targetFileName);
bos = new BufferedOutputStream(out);
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
connection = factory.createConnection();
connection.start();
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue("queue1");
consumer = session.createConsumer(destination);
logger.info("--init end--");
}

public void receiveFile(String targetFileName) {
logger.info("--receive file start--");
try {
init(targetFileName);
byte[] buffer = new byte[2048];
while (true) {
Message msg = consumer.receive(5000);
if (msg == null) {
break;
}

if (msg instanceof StreamMessage) {
StreamMessage smsg = (StreamMessage) msg;
int c = smsg.readBytes(buffer);

String tempStr = new String(buffer, 0, c);
logger.info("Receive str: " + tempStr);
bos.write((tempStr).getBytes());
}
}
logger.info("--receive file end--");
} catch (Exception e) {
logger.error("--sendFile fail--", e);
} finally {
close();
}
}

private void close() {
logger.info("--consumer close start--");
try {
if (bos != null) {
bos.close();
}
if (bos != null) {
bos.close();
}
if (connection != null) {
connection.close();
}
logger.info("--consumer close end--");
} catch (IOException e) {
logger.error("--close OutputStream fail--", e);
} catch (JMSException e) {
logger.error("--close connection fail--", e);
}
System.exit(0);
}

public static void main(String[] args) {
new StreamConsumer().receiveFile("/home/kuntal/practice/config-data/output2.txt");
}

}

Hope this help you and saves your valuable time!!