|
|
||
Masoud Kalali's BlogMay 2006 ArchivesStep by Step toward a jms sample in NetBeans and yes GlassFish. part 2 : Remote ClientPosted by kalali on May 10, 2006 at 06:01 AM | Permalink | Comments (0)In previous part you saw that how easy is to make an MDB to consume messages and a jsp/Servlet Front End to send message to a queue. in this part i will show you how you can send message to a queue from a remote j2se client. you should know that in jms sending and reciving mesages has similar steps , some small changes require to consume message from a j2se client instead of sending messages. to make it more clear , the main purpose of an MDB is to consume messages as they arrive , The MDB onMessage(..) is called whenever a message become available in destination that MDB is binded to it. sure we can do what ever we want after message recieved. for example you can send the message that you recive from a queue to several topics , you can process it to do some database operation.... usually we use JMS for executing Asynchronous operations ,bringing more decoupling of a system components.... but lets come to our own steps to create a simple remote client that will sends some messages to tQueue that we made in first part of this series. then we will see that our messages are reciveing by TMDB. As you know we used a context object to locate the Queue and ConnectionFactory . the servlet code was like: ... Context ctx = new InitialContext(); ...By default a JNDI client assume that it is in a correctly configured environment , so when we do not pass a HatshTable to IinitialContext , the InitialContextFactory will return a context configured with that environment .In server environment we do not need to explicity pass parameters to InitialContext unless we need to initiate a context for another environment. But, what are this parameters and how we can use them to initiate a context for none default environemtn or in places that there is no default environemt pre-configured , situation like standalone remote clients? in a such situation we should configure the InitialContext using a HashTable that contain some parameters, There are several parameter that can be used to configure the initialContext but Two most important ones are :
I should tell that we can also make this parameter to be the jvm default parameter and allows the Initialcontext to return a context without need to pass any arguments. in this way we need to pass parameters to java command when we want to start it. for example you can use : java -Djava.naming.provider.url="iiop://127.0.0.1:3700" -Djava.naming.factory.initial="com.sun.appserv.naming.S1ASCtxFactory" to start our application. this way you allows the Initialcontext to return a context without need to configure it by a HashTable. For our Sample we will use a hashtable to configure the InitialContext , but you can try to pass parameters to java instead and observ the execution of your application. To create a j2se remote client we need to add some jar files to our project , NetBeans provide its own way to manage jar files that may be used in more than one project. it is Libraries.... Run NetBeans, From Tools menu select Library Manager , create a new library and name it jms . Now you can add as much jar files to this library as you need , then it will be reuseable for your other projects. add following jar files to this library , I use glassfish_home as installation directory of glassfish.
Create a j2se project using , File > new project > general > java application. name the application jmsClient and allow the IDE to create a Main class for you. You shoud add that library that you create to this project. to do this , expand the project node , right click on the libraries and select add library Now from the library list select jms . Up to now you have done 30% of creating an stand alone remote client to interact with your jms resources like connectionFactories and destinations. Now we need to code the main method of main class . expand the jmsClient node , expand the source packages and finally open the main class of your project. The overall look of your code shoul be like the following :
public class JmsClient {
Context ctx;
public JmsClient() {
Hashtable properties = new Hashtable(2);
properties.put(Context.PROVIDER_URL,"iiop://127.0.0.1:3700");
properties.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.appserv.naming.S1ASCtxFactory");
try {
ctx = new InitialContext(properties);
} catch (NamingException ex) {
ex.printStackTrace();
}
}
public Object lookup(String name){
try {
return ctx.lookup(name);
} catch (NamingException ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
JmsClient client = new JmsClient();
try{
ConnectionFactory connectionFactory = (ConnectionFactory)client.lookup("jms/tConnectionFactory");
Queue queue = (Queue)client.lookup("jms/tQueue");
javax.jms.Connection connection = connectionFactory.createConnection();
javax.jms.Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE);
MessageProducer messageProducer = session.createProducer(queue);
for(int i=0;i<5;i++) {
TextMessage message = session.createTextMessage("It is a message from main class "+ ": "+ i);
System.out.println( "It come from main class:"+ message.getText());
messageProducer.send(message);
}
} catch(Exception ex){
ex.printStackTrace();
}
}
}
Now lets see what the above code means , i will not go indepth because JMS APIs are discussed too much :-) . In constructor we configured a context object named ctx we encapsulate the lookpu task in a method named lookup(...) we usually use a service locator or cached service locator to locate our objects in JNDI because JNDI lokups are time consumer In main method:
Now lets run the program and see the result , to run the application you nedd to complete the first part of this series , then you should run the application server , and if you like to have a demonestration like what i will show you , you should deploy the application that we made in first part. i assume you have completed first part and you have the application server running , Now run the client that we made and what you will see in output window should be like : and if you take a look at application server log file (in runtime tab , expand the servers node and rigt click on the glassfish instance , now select view server log..) what you should see in the server log should be something like : messages that we send via standalone client will reach the queue that the MDB is listening on it , as soon as we send a message MDB will pick it up and start processing it. you can download the standalone client project from here GlassFish is Open source , but how much Open it is ?Posted by kalali on May 09, 2006 at 02:07 AM | Permalink | Comments (0)We know that GlassFish is opensource under CDDL license , being opensource is good but having a good and open relation with community is very good. GlassFish has the most active community between opensource project that i have been involve a bit closer than observing , having that TheAquarium weblog make it magnifisant.Meanwhile you think that that weblogs is available in more that 3 languages, and it shows how much hard GlassFish people works to provide community with information that they need. its Wiki is a great source of information and shows how much far GlassFish people goes in making a good communication with the community. wiki pages update very often , you will find new information in its wiki / weblogs whenever you look at them.I think there is more with this glassfish to reveal than being just reference implementation of Java EE 5. if you check TheAquarium in a daily basis you will see that Glassfish components are going to Maven repository of java .net very fastly , and it means that we can use maven for our project which are based on java ee 5. Step by Step toward a jms sample in NetBeans and yes GlassFishPosted by kalali on May 05, 2006 at 06:40 AM | Permalink | Comments (4)Java EE 5 brings many ease of use in EJB development world and certainly it is one of biggest step ahead in java EE land. NetBeans 5.5 is another big step toward making development on top Java EE some easier. NetBeans is a very easy to learn and use because it does not bring many stuff on the screen to "Occupy all the space" instead it provide maximum useability by means of limited number of views. GlassFish as Reference implementation of JAVA EE 5 , provide you with all service that are named in java EE spec but it is not similar to older RI version of J2EE ,just remember J2EE 1.3 RI it is much more better in term of functionality, performance, ease of use and ... here I will tell you steps that you need to follow to build a simple MDB , a web based message producer and a remote message producer. when you follow this entry you will be able to deal with basic aspect of JMS in Action and not only on your papers. but what do we need to have our JMS application running ?
To create Queue and connection follow these steps :
go to project view , right click on EJB module and select NewMessage-Driven Bean... a window will open and ask you for some attributes of this MDB fill in the names like :
*** This is where our MDB is assigned to , whether it is a topic in publish/subscribe scenario or a queue in point-to-point scenario. Now change the implementation of your onMessage(...) as following , we also add one private object to our class , make sure that you include it too.
@Resource
private MessageDrivenContext mdc;
public void onMessage(Message message) {
TextMessage msg = null;
try {
if (message instanceof TextMessage) {
msg = (TextMessage) message;
System.out.println("A Message received in TMDB: " +
msg.getText());
} else {
System.out.println("Message of wrong type: " +
message.getClass().getName());
}
} catch (JMSException e) {
e.printStackTrace();
mdc.setRollbackOnly();
} catch (Throwable te) {
te.printStackTrace();
}
}
we just made one more change in class skeleton and that is our MessageDrivenContext variable , we usually use this to call setRollbackOnly(...) when we use an MDB in a transactional scenario for this sample you simpley can ignore it. Now lets make our web application to send some messages to that Queue and let the MDB fetch and process them. wxpand web application node , and double click on index.jsp after it opens , change its content like the following , sure you can use component platte to drag and drop items to jsp source file :-) <%@page contentType="text/html"%> <%@page pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <center> <form action="sendMessage"> <table cellspacing="20" > <tbody> <tr> <td>Enter some message: </td> <td><input type="text" name="message" value="Enter your message here" width="30" /></td> </tr> </tbody> </table> <input type="submit" value="Send The message" name="send" /> </center> </form> </body> </html> Now we need to build a servlet , which will send messages to our Queue , for this task you need to do these steps :
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); //start the jms stuff try{ Context ctx = new InitialContext(); ConnectionFactory connectionFactory = (ConnectionFactory)ctx.lookup("jms/tConnectionFactory"); Queue queue = (Queue)ctx.lookup("jms/tQueue"); javax.jms.Connection connection = connectionFactory.createConnection(); javax.jms.Session session = connection.createSession(false,Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(queue); TextMessage message = session.createTextMessage(); message.setText(request.getParameter("message")); System.out.println( "It come from Servlet:"+ message.getText()); messageProducer.send(message); //message sent , it was all //show what we have done in this servlet out.println("<html>"); out.println("<head>"); out.println("<title>Servlet sendMessage</title>"); out.println("</head>"); out.println("<body>"); out.println("<center>"); out.print("Servlet Send this message <h2>"+request.getParameter("message") + "</h2> to this Queue : <h2>"+queue.getQueueName()+"</h2>"); out.println("</center>"); out.println("</body>"); out.println("</html>"); } catch(Exception ex){ ex.printStackTrace(); } out.close(); } It was all you should do to create a JMS point to point sample. to view what you have Done , press F6 , if you did all the above as i said you will see a page like : Now just give it a message and press the button , what you will see should looks like the following image , in case that your praise the NetBeans and GlassFish as i did ;-) and if you look at Application server log file , you will see something similar to : (to view the application server log file go to runtime view , right click on glassfish node and select view log file) You can download the project from here but make sure that you build the connection factory and queue because project will need them . In next part i will show you how easily you can make a remote client to deal with your jms destinations. | ||
|
|