Tuesday, January 31, 2012

Sample Code For Spring JMS Template with HornetQ Messaging System in JBoss-5.1 Server

Dear Chennai Java Buddies,

****** : For Any Clarifications, Doubts
Mail to : Balaji.mathu@gmail.com



Here I am giving sample code, configuration for Create JMS Queue in Jboss with 3rd Party Messaging System (HornetQ). And giving spring configuration, code to send and receive messages throught the Queue.


HornetQ Introduction & Why we go for:


1> HornetQ is an open source project to build multi-protocol (TCP, SSL, Servlet), embeddable, very high performance, clustered, asynchronous Messaging System from JBoss.
2> It can be used as standalone, or on any application server, or embedded in our applications.
3> It delivers amazing messaging performance.
4> It provides seamless clustering capabilities.
5> Most Important: It is the default messaging system in JBoss-6.0 / forthcoming JBoss Servers.
6> Security Features of JBoss – JAAS can be implemented.



HornetQ Installation on JBoss Server 4.x/ 5.x:


1> Download the latest from http://www.jboss.org/hornetq/downloads.html. Extract it.
2> As we want to embed HornetQ in JBoss we have to run the script build.sh located in “ HORNETQ-HOME/config/jboss-as-4” or “ HORNETQ-HOME/config/jboss-as-5”. Before that we have to set up JBOSS_HOME path.
3> After the script ran it will create two additional JBoss configurations in JBoss are “default-with-hornetq” and “all-with-hornetq” inside /server folder. These folders have the configurations files for HornetQ.
4> Also the needed HornetQ API jars will be created in JBoss’s lib folder. So now the JBoss is ready with HornetQ.


1. HornetQ Queues Configuration in JBoss:
/Servers/jboss-5.1/server/default/deploy/hornetq.sar/hornetq-jms.xml
----connection-factory name="MyConnectionFactory"--
----connectors--
----connector-ref connector-name="in-vm"/--
----/connectors--
----entries--
----entry name="java:jms/MyConnectionFactory"/--
----entry name="java:jms/MyConnectionFactory"/--
----/entries--
----/connection-factory--
----queue name="myQueueOne"--
----entry name="java:jms/queue/myQueueOne"/--
----durable--true--/durable--
----/queue--

--queue name="myQueueTwo"--
--entry name="java:jms/queue/myQueueTwo"/--
--durable--true--/durable--
--/queue--

2. Spring JMS Template Configuration:
2.1 ~/MyApplication.war/WEB-INF/config/spring/jndi-lookup.xml

--?xml version="1.0" encoding="UTF-8"?--
--beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd"--
--jee:jndi-lookup id="connectionFactory" jndi-name="java:jms/MyConnectionFactory" resource-ref="true"/--
--jee:jndi-lookup id="myQueueOne" jndi-name="java:jms/queue/myQueueOne" resource-ref="true"/--
--jee:jndi-lookup id="myQueueTwo" jndi-name="java:jms/queue/myQueueTwo" resource-ref="true"/--
--/beans--


2.2 ~/MyApplication.war/WEB-INF/config/spring/jms-listener.xml
--?xml version="1.0" encoding="UTF-8"?--


--beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
xmlns:jms="http://www.springframework.org/schema/jms"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jms http://www.springframework.org/schema/jms/spring-jms-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd"--
--bean id="queueOneTemplate" class="org.springframework.jms.core.JmsTemplate"--
--property name="connectionFactory" ref="connectionFactory" /--
--property name="defaultDestination" ref="myQueueOne" /--
--property name="pubSubDomain" value="false" /--
--property name="receiveTimeout" value="1000" /--
--/bean--
--bean id="queueTwoTemplate" class="org.springframework.jms.core.JmsTemplate"--
--property name="connectionFactory" ref="connectionFactory" /--
--property name="defaultDestination" ref="myQueueTwo" /--
--property name="pubSubDomain" value="false" /--
--property name="receiveTimeout" value="1000" /--
--/bean--
--!—My Queue Listeners ----
--bean id="queueOneListener"
class="com.test.jms.msg.listeners.MyQueueOneListener"--
--/bean--
--bean id="queueTwoListener"
class="com.test.jms.msg.listeners.MyQueueTwoListener"--
--/bean--


--!-- Container for MyQueue Message and Delegation ----
--bean id="queueOneContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer"--
--property name="taskExecutor" ref="mdpPoolTaskExecutor" /--
--property name="connectionFactory" ref="connectionFactory" /--
--property name="messageListener" ref="queueOneListener" /--
--property name="destination" ref="myQueueOne" /--
--property name="concurrentConsumers" value="5" /--
--property name="maxConcurrentConsumers" value="50" /--
--property name="pubSubDomain" value="false" /--
--property name="cacheLevelName" value="CACHE_CONSUMER" /--
--property name="idleTaskExecutionLimit" value="100" /--
--property name="sessionTransacted" value="true" /--
--property name="autoStartup" value="true" /--
--/bean--

--bean id="queueTwoContainer"
class="org.springframework.jms.listener.DefaultMessageListenerContainer"--
--property name="taskExecutor" ref="mdpPoolTaskExecutor" /--
--property name="connectionFactory" ref="connectionFactory" /--
--property name="messageListener" ref="queueTwoListener" /--
--property name="destination" ref="myQueueTwo" /--
--property name="concurrentConsumers" value="1" /--
--property name="maxConcurrentConsumers" value="5" /--
--property name="pubSubDomain" value="false" /--
--property name="cacheLevelName" value="CACHE_CONSUMER" /--
--property name="idleTaskExecutionLimit" value="100" /--
--property name="sessionTransacted" value="true" /--
--property name="autoStartup" value="true" /--
--/bean--
--bean id="mdpPoolTaskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor"--
--property name="corePoolSize" value="5" /--
--property name="maxPoolSize" value="50" /--
--property name="queueCapacity" value="250" /--
--property name="threadNamePrefix" value="MDP-WorkerThread" /--
--/bean--

--/beans--


3. Application Code to Perform Messaging:
3.1 com.test.jms.msg.listeners.MyQueueOneListener

package com.test.jms.msg.listeners;

import java.util.StringTokenizer;
import java.util.concurrent.Executor;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import org.springframework.jms.core.JmsTemplate;


/**
* @author balaji_madhaiyan
*
*/
public class MyQueueOneListener implements MessageListener
{
private JmsTemplate actionRequestTemplate,actionResponseTemplate;
public void onMessage(Message mesg)
{
System.out.println("New Message Received");
ObjectMessage msg = (ObjectMessage) mesg;
try
{
MessageDO vo = (MessageDO) msg.getObject();
String str = null;
str = vo.getMsg();
System.out.println("Message Received at MyQueueOneListener:"+ str);
}
catch (JMSException e)
{
System.out.println("Error at MyQueueOneListener : "+e.getMessage());
}
}

3.2 com.test.jms.msg.listeners.MyQueueTwoListener
package com.test.jms.msg.listeners;

import java.util.StringTokenizer;
import java.util.concurrent.Executor;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;
import org.springframework.jms.core.JmsTemplate;


/**
* @author balaji_madhaiyan
*
*/
public class MyQueueTwoListener implements MessageListener
{

private JmsTemplate actionRequestTemplate,actionResponseTemplate;
public void onMessage(Message mesg)
{
System.out.println("New Message Received");
ObjectMessage msg = (ObjectMessage) mesg;
try
{
MessageDO vo = (MessageDO) msg.getObject();
String str = null;
str = vo.getMsg();
System.out.println("Message Received at MyQueueTwoListener:"+ str);
}
catch (JMSException e)
{
System.out.println("Error at MyQueueOneListener : "+e.getMessage());
}

}
3.3 com.test.jms.msg.listeners.MyMessageDO
package com.test.jms.msg.do;

import java.io.Serializable;
public class MessageDO implements Serializable
{

private String type;
private String msg;

public MessageDO(String type, String msg)
{
super();
this.type = type;
this.msg = msg;
}


public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public String getMsg()
{
return msg;
}
public void setMsg(String msg)
{
this.msg = msg;
}
}


3.3 com.test.jms.msg.listeners.MyMessageSender
package com.test.jms.msg.senders;

import java.util.List;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.scheduling.annotation.Scheduled;
import com.test.jms.msg.listeners.MyMessageDO;
import com.test.jms.msg.listeners.MyQueueTwoListener;
import com.test.jms.msg.listeners.MyQueueTwoListener;

public class MyMessageSender
{
@Autowired
private JmsTemplate queueOneTemplate, queueTwoTemplate;

//To Queue One
private void pushToQueueOne()
{
queueOneTemplate.send(new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
ObjectMessage msg = session.createObjectMessage();
MessageDO dObj = new MessageDO("Msg", message);
msg.setObject(dObj);
return msg;
}
});
}
//To Queue Two
private void pushToQueueOne()
{
queueTwoTemplate.send(new MessageCreator()
{
public Message createMessage(Session session) throws JMSException
{
ObjectMessage msg = session.createObjectMessage();
MessageDO dObj = new MessageDO("Msg", message);
msg.setObject(dObj);
return msg;
}
});
}
}


Thursday, August 19, 2010

Servlet JSP Interview Questions

1.    What is JSP?
Answer: Server-side running program technology helps to create dynamic, platform independent web based applications.
2.    What is Servlet?
Answer: Servlet is a java program runs on server, which receive request and send responses on HTTP protocol.
3.    Tell me Servlet Life Cycle?
Answer:   web server loads class->instantiate () -> calls init()-> calls service() on each request->calls destroy() on unloading from server -> unloaded from server.
4.    Tell me JSP Life Cycle?
Answer:   jspInit() -> _jspService() -> jspDestroy().
5.    What is the difference doGet() and doPost()?
Answer: 
doGet() –Used for query process, which processes only HTTP GET requests which contains less input data like URL params
doPost() –Used to send some data, do some processes and get output. Processes HTTP POST requests which contains more data.
6.    Have you called Servlets in JSP?
Answer:
<%@ page import = "javax.servlet.RequestDispatcher" %>
<% RequestDispatcher rd = request.getRequestDispatcher("/yourServletUrl");
     request.setAttribute("msg","HI Welcome");
     rd.forward(request, response);
%>
OR
OR
7.    How will you declare a method inside JSP?
Answer:
Script let: Used to execute Java code <% out.print(“HelloWorld JSP”)%>
Expression: Used to display on output stream. <%= Calendar.getInstance().getTime()%>
Declaration: Used to declare methods and variables <%! %>
8.    What is mean by Single Thread Model in Servlet?
Answer: By default Servlets are Multithreaded, i.e. single servlet responds for multiple requests. But we can configure to instantiate each new instance for each requests (Single Threaded Model) by implementing interface SingleThreadedModel.
9.    What is Declaration in JSP?
Answer: Declaration: Used to declare methods and variables inside JSP and on compiling they are placed outside _jspService method: syntax is <%! Int a=5;%>
10. After Compiling JSP, does declaration available within _jspService method?
Answer: Declarations of methods and variables will be place outside of the _jspService() method in the class file after compilation.
11. How can two servlets communicate?
Answer:
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);
Or
Response.sendRedirect(“URL”);
12. How a JSP page communicate with another servlet?
Answer: Using
OR
RequestDispatcher rd = servletContext.getRequestDispatcher("/pathToResource");
rd.forward(request, response);
OR
Response.sendRedirect();
13. Explain Servlet Container’s Single-Thread Model and Multi-Thread Model?
Answer: All servlets by default instantiated only once by the container and same one instance responds for all incoming requests. But by implementing SingleThreadModel for each request new instance will be created, serviced and destroyed.
14. What are the service methods in HTTPServlet?
Answer:
doGet() –  only for querying/getting data from server
doPost()-  for posting data to the server and ask it to process. Secured.
doPut()-   Just add data into the URL
doHead() – get Header part of the Get URL
doTrace() – traces loopback
doDelete() – Delete the requested url
doOptions() – Get list of methods.
15. Difference between GenericServlet and HTTPServlet?
Answer:
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. GenericServlet class can handle any type of request so it is protocol-independent.
But the HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods.
16. Can init() method called many times?
Answer: Yes if u make singlethreadedmodel. But by default called only once.
17. Use of "load-on-start-up" parameter in Web.xml?
Answer: It denotes that servlet to be loaded by container very first.
18. How do you manage Session in Servlets and JSP?
Answer: Session is a conversation state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response.
a)    Authenticating each time
b)    Hidden fields in forms of jsp
c)    Cookies
d)    URL rewriting
e)    Session API
19. How to use Cookies in JSP?
Answer:
Cookie cook = new Cookies(“userid”, “232314”);
Response.addCookie(cook);

So these will be stored in browser and will be returned each time.

Get Cookie:
Cookie cooks[] = Request.getCookies();

Delete Cookies:
Cooks[0].setMaxAge(200);
20. How to use HTTPSession in JSP?
Answer:
          HttpSession session=request.getSession(false);  
          String n = (String)session.getAttribute("uname");  
Also set value:
Session.setAttribute(“uId”,”12313123”);
21. What are the methods of HTTP Session?
Answer:
getAttribute(), setAttribute(), isNew(), invalidated(), removeAttribute(), setMaxTime()

22. How will you send a request to another servlet?
Answer:
RequestDispatcher rd= ServletContext.getRequestDispatcher(“URL”);rd.forward(req,resp);
23. What is the difference between sendRedirect and forward method?
Answer: RequestDspatcher().forward – happens inside container only.
Response.sendRedirect – server – client – another server
24. Explain about Request-dispatcher?
Answer: An interface receive requests from client and forwards to another resource on same server.
25. Explain about HTTPSession-Listener? What are the methods?
Answer: Two methods:
sessionCreated(HttpSessionEvent e)
sessionDestroyed(HttpSessionEvent e)
26. What is the immediate super class of HTTPServlet?
Answer: http.servlet.GenericServlet class
27. What is the difference between ServletContext and ServletConfig?
Answer:
ServletConfig – used by server to pass parameters to servlets while initializing, available within the scope of Servlet.
ServletContext – contained by servletConfig and used by .getContext(). Used by servlet to communicate with container.
28. What do u mean implicit object and list out implicit objects?
Answer:
Out – represents object of javax.servlet.jsp.JspWriter and is used to send content in response.
Request –represents object of HttpServletRequest sent from client.
Response – represents object of HttpServletResponse produced by JSP to send to client.
Config – represents objects of ServletConfig of the servlet of the JSP.
Application – represents ServletContext
Session – represtents the object of HttpSession associated with the Servlet.
pageContext – PageContext – used to set/remove attributes to any of the 4 scopes.
         Ex: pageContext.removeAttribute("attrName", PAGE_SCOPE);
page – represents “this” of the servlet.
exception –Throwable- any exception occurs will be catched and thrown to the “errorPage” if mentioned.

29. What is directive?
Answer:
The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.
Page Directive:  The page directive defines attributes that apply to an entire JSP page
   Ex: isErrorPage, errorPage, import, extends etc.,
Include Directive:  The include directive is used to include the contents of any other resource it may be jsp file, html file or text file<%@ include file=”header.jsp”>
TagLibrary: Declared tag libraries custme actions.  
30. What is mean by Custom Tag? What are all the JSP Standard Tag Libraries?
Answer:
public class HelloTag extends SimpleTagSupport
{
    public void doTag() throws JspException, IOException
{
           JspWriter out = getJspContext().getOut();
          out.println("Hello Custom Tag!");
          }
}
WEB-INF/Custom.tld
  1.0
  2.0
  Example TLD
 
    Hello
    com.tutorialspoint.HelloTag
    empty
 
Test.jsp
<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
 
    A sample custom tag
 
     
 


31. What is EL & use?
Answer: Helps to use the POJO varaibles in page. ${emp.FirstName}
32. What is mean by MVC Architecture in JSP?
Answer:
Servlet as – Controller - will receive request – validate – forms Model POJP Bean – Delegates to JSP 1 or JSP 2 based on the values.
JSP1.jsp or JSP2.jsp – as View
Employee.java – POJO as Model
33. I want to restrict a page should be shown only when session exists, How to do that?
Answer: If we add page directive session=false then we can restrict the session object creation in particular JSP page.
34. I want to handle exceptions in JSP page, How to do that?
Answer: Create a special error page and add it using page directive errorPage=”err.jsp”. So all errors will be redirected automatically to err.jsp. err.jsp page should include isErrorPage=”true”.
35. What are the two different ways to include in JSP?
Answer:
1.    Page Directive Include : <%@ include page=”header.jsp’/> - Static include means will be included on compilation. And will be created as single servlet class.
2.    Tag library Include :< jsp:include page=”header.jsp”/> - Is runtime inclusion, so content of the jsp/html file will be included into the output writer.
36. Can session contain primitive types?
Answer:
HTTPSession session = new HTTPSession ();
Session.setAttribute (“regId”, 123123);
37. What are the types of scope s available in JSP?
Answer:
Page – available within the same page only. It exist from request creation to server processing. After server process it dies.
Request – available within the request i.e., if it forwarded to multiple pages it exists.
Session – Objects exists and live from request creation to till the browser closed.
Application – Accessible from multiple JSP pages of application, added to application context.
38. How will you declare variables and method in JSP?
Answer: Using Declarations <%! Int a=5; int add(int a,int b){ return a+b;}%>
39. How to access POJO beans in jsp?
Answer:
setValues to bean in JSP1.jsp
getValues from Bean and display in JSP2.jsp

You entered
Name: <%= user.getUsername() %>
40. Have you used filters?
Answer: Yes. MyLogFilter implements javax.servlet.Filter used to print log of all incoming request details. It has three methods like servlets init(), doFilter() and destroy(). These should have be configured in web.xml.
We can add multiple listeners so they are all will be sequentially processed before the request passed to the respective servlet.
41. What are the listeners you have used?
Answer: There are
ServletRequestListener
requestInitalized
requestDestroyed

ServletRequestAttributeListener
attributeAdded
attributeRemoved
attributeReplaced

ServletContextListener
contextInitalized
contextDestroyed

ServletContextAttributeListener
attributeAdded attributeRemoved
attributeReplaced

HttpSessionListener
sessionCreated
sessionDestroyed

HttpSessionAttributeListener
attributeAdded
attributeRemoved
attributeReplaced

HttpSessionBindingListener
valueBound
valueUnbound

HttpSessionActivationListener