J2EE

"J2ee "

This Section focuses on Servlets,JSPs,JNDI,EJB,JMS.

1 )   What is J2ee ?

Ans)

  • What is J2ee ?
    Sample Img 1
J2EE includes a number of components such as the following:
Enterprise JavaBeans, EJB is a server-based technology for the delivery of program components in an enterprise environment.
The Java servlet API (application programming interface) enhances consistency for developers without requiring a graphical user interface (GUI).
Java Server Pages (JSP) is the Java equivalent to Microsoft's Active Server Pages (ASP) and is used for dynamic Web-enabled data access and manipulation.

Java Message Service (JMS), Java's message oriented Programming model. Also JNDI, RMI, JCA, JTA etc.,

2 )   Typical J2ee Architecture

Ans)

  • Typical J2ee Architecture
    Sample Img 2
 Client Tier :
Client-tier components run on the client machine such as Browsers,
or standalone Applications.
Web Tier :
Web-tier components run on the J2EE server such as JSP, Servlet or
other frameworks such as Struts , Spring etc.,
Business Tier :
Business-tier components run on the J2EE server such as EJB, RMI,JMS etc.,
ESI Tier   :
Database Servers

3 )   Web Server VS Application Server ?

Ans)

  • Web Server VS Application Server
    Sample Img 3
A Web server exclusively handles HTTP requests, whereas an application server serves business logic to application programs through any number of protocols.
     A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology.
    As for the application server, according to our definition, an application server exposes business logic to client applications through various protocols, possibly including HTTP, RMI. In most cases, the server exposes this business logic through a component API, such as the EJB (Enterprise JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers.



    4 )   What is a Servlet ?

    Ans)
    A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes.
    public class SomeServlet extends HttpServlet {
      public void doGet(HttpServletRequest request,
                        HttpServletResponse response)
          throws ServletException, IOException {
        }
    }

    5 )   What is the difference between HttpServlet and GenericServlet?

    Ans)
    GenericServlet is for servlets that might not use HTTP, like for instance FTP servlets. Of course, it turns out that there's no such thing as FTP servlets, but they were trying to plan for future growth when they designed the spec. Maybe some day there will be another subclass, but for now, always use HttpServlet.

    6 )   What is Servlet Life Cycle ?

    Ans)

    • Servlet Life Cycle
      Sample Img 6
    init() , service(),destroy() are Servlet LifeCycle methods. See below for more details
    Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file.
    Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method.
    Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
    Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet.

    7 )   How many times init () will be called ?

    Ans)
    init() method will be invoked only once in Servlet Life Cycle by Servlet Container, this could be overriden by you.
    In most of the cases if you do one-time tasks such as  loading the applications properties or reading Configurations  could be done in
    This method. Please see below for more details.
               public void init(ServletConfig config) throws ServletException {
                    super.init(config);
            
                    try {
                        String log4jPropFileName = null;
                         String legacyServiceConfig = getInitParameter(LEGACY_CONFIG);
                        log4jPropFileName = legacyProp.getProperty(LOGGING_PROPERTIES);
                        if (log4jPropFileName != null) {
                            URL url = Logger.class.getClassLoader().getResource(log4jPropFileName);
                        }
                }

    8 )   How could you have two or more Servlets in your web application ?

    Ans)
    We can have any number of Servlets in any web application, Servlet  loading priority to be set as shown below
    with " <load-on-startup>1</load-on-startup>"  ,  if "load-on-startup" is 1 for any given Servlet, that will be loaded
    first .
     <servlet>
      <servlet-name>Init</servlet-name>
      <servlet-class>
                com.InitServlet
            </servlet-class>

      <init-param>
       <param-name>loggingLevel</param-name>
       <param-value>1</param-value>
      </init-param>
      <init-param>
       <param-name>propertiesFile</param-name>
       <param-value>/WEB-INF/properties/yourconfig.xml</param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
     </servlet>
     <servlet>
      <servlet-name>DetailServlet</servlet-name>
      <servlet-class>
                com.PropertyDetailsServlet
            </servlet-class>
     </servlet>

    9 )   Can I create a Servlet Instance and invoke that from a Main method ?

    Ans)
    In reality this would not make sense to create a Servlet from a main(string str[]) {},
    but  you could , in that case the Servlet just behaves like a Plain Java class, no life-cycle methods
    would be invoked , container will not manage the Servlet Life-Cycle.
    If you want invoke a Servlet from a standlone class please use HttpURLConnection or some
    Httpclient like Apache etc.,
     URL url = new URL(strUrl);
     HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
     urlConn.connect();

    10 )   What is the Servlet Container ?

    Ans)
    A Web container (also known as a Servlet container) is essentially the component of a Web server that interacts with the servlets. The Web container is responsible formanaging the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

    11 )   How would you make your servlet work for both GET and POST http requests ?

    Ans)
    If you write a Servlet as shown below that could work fine for both POST as well as GET Http Requests.
    public class CommonServlet extends HttpServlet {
            protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                            throws ServletException, IOException {
                    doProcess(req, resp);
            }
            protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                            throws ServletException, IOException {
                    doProcess(req, resp);
            }
            private void doProcess(HttpServletRequest req, HttpServletResponse resp) {
            //write your code
            }
    }

    12 )   What is Servlet Context ? How would two Servlets Communicate ?

    Ans)
    A ServletContext represents the context in a servlet container of a servlet instance operates. A servlet container can have several contexts (or web applications) at one time. Each servlet instance is running in one of these contexts. All servlets instances running in the same context are part of the same web application and, therefore, share common resources. A servlet accesses these shared resource (such as a RequestDispatcher and application properties) through the ServletContext object.
    The Servlets that are in same ServletContext could be communicated with  "getRequestDispatcher" as shown below.
                  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/web/test.jsp");

    13 )   What is Servlet Config ? How would we pass Init Parameters to a Servlet ?

    Ans)
    The ServletConfig defines how a servlet is to be configured is passed to a servlet in its init method. Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters. The container, in turn, passes these parameters to the servlet via the ServetConfig. 
    Please take a look at the sample below , the Init-Param "config" could be read by using "ServletConfig" in init(ServletConfig config)  method.
      <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
         <init-param>
          <param-name>config</param-name>
          <param-value>/WEB-INF/struts-config.xml</param-value>
        </init-param>

        <load-on-startup>2</load-on-startup>
      </servlet>

    14 )   RequestDispatcher.forward() VS Response.sendRedirect () ?

    Ans)
    Since forward() method of RequestDispatcher is handled on the server ,therefore the request and its associated session are
    available to the forwarded resource
     and you can pass data between them using request.setAttribute(). forward() separates the
    responsibilities for handling the requests among several components. This method generally sends a request and response
    object to resources (servlets or JSP's) of the same ServletContext.
    RequestDispatcher.forward() and PageContext.forward() are effectively the same
           RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/web/tes.jsp");
           dispatcher.forward(req, resp);
    sendRedirect() method of a response object sends the url  to the browser that includes the parameter of sendRedirect()
    method Browser treats this a new request from the client. sendRedirect() forwards a requests to a resource outside of the
    current web application. Using sendRedirect is similar to open a new browser and type your url. A sendRedirect() also updates
    the browser history and transfers control only when the whole service method completes. There is only one way to pass data is
    through the session or using web parameters (url?name=value).
      resp.sendRedirect(""/web/tes.jsp");      // Considered as new Request in the browser

    15 )   Servlet SingleThreadedModel ?

    Ans)
    Ensures that servlets handle only one request at a time. This interface has no methods.
    If a servlet implements this interface, you are guaranteed that no two threads will execute concurrently in the servlet's service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instances and dispatching each new request to a free servlet.
    Note that SingleThreadModel does not solve all thread safety issues. For example, session attributes and static variables can still be accessed by multiple requests on multiple threads at the same time, even when SingleThreadModel servlets are used.

    16 )   How you read QueryString and URI of a given http request ?

    Ans)
    String queryString = req.getQueryString();

    17 )   What is Request Scope ?

    Ans)
    There are three places a servlet can save data for its processing – in the request, in the session (if present), and in the servlet context (which is shared by all servlets and JSP pages in the context). Data saved in the request is destroyed when the request is completed. Data saved in the session is destroyed when the session is destroyed. Data saved in the servlet context is destroyed when the servlet context is destroyed.
    Data is saved using a mechanism called attributes. An attribute is a key/value pair where the key is a string and the value is any object.
    // Save and get a request-scoped value
    req.setAttribute("userName", "testUser");
    Object value = req.getAttribute("userName");
    // Save and get a session-scoped value
    HttpSession session = req.getSession(false);
    if (session != null) {
        session.setAttribute("userName", "testUser");
        value = session.getAttribute("userName");
    }
    // Save and get an application-scoped value, could be accessed by all Servlets/Jsps in that web application
    getServletContext().setAttribute("userName", "testUser");
    value = getServletContext().getAttribute("userName");

    18 )   Is http Stateless ? How could you maintain the state in a Web Application ?

    Ans)
    Yes HTTP is stateless, meaning every request is being treated as a new one and
    state (data) will not be shared between two http requests, but Servlet
    API provide  the some mechanisms address this issue. Below are Servlet
    state management techniques.
    i) Use POST/GET variables to pass info from page to page.  (Hidden Variables)
         <input type='hidden' name='userName'>
         request.getParameter ('userName');

    ii) Use the session to store information.
         session.setAttribute("userName", "testUser");
         value = session.getAttribute("userName");

    iii) Use cookies to store information.
         Cookie cookie = new Cookie("CName","Cookie Value");
        cookie.setMaxAge(100);
        response.addCookie(cookie);

    19 )   What are the disadvantages of putting too much data in HTTP Session ?

    Ans)
    If you have more data into your HTTPSession object , following could be some of the issues you may encounter.
    • May cause Memory issue when you have max sessions opened at a given point of time.
    • This also causes read/write overhead, though your application wants a fraction of data from such a big Object graph you app server has to load Full HTTPSession.
    • This is going cause performance issue when you make your application clusterable due to Session Replication, with which your data modifications would be replicated on all other members of the Cluster.
    This is too expensive if you have opted for "Persisted HttpSessions" in your App server. 

    20 )   How you write the Servlet Output to a File ?

    Ans)
    If want to write your Servlet Output a File such as a XML file or TXT or Doc, you simply set the MIME type as shown below.

    21 )   How you upload a file to Servlet ?

    Ans)
    There are several ways of doing this, below are some of them.
    By using commons-fileupload
    protected void doPost(
    HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
     try {
     List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
         for (FileItem item : items) {
     if (item.isFormField()) {
    String fieldname = item.getFieldName();         
     String fieldvalue = item.getString();        
       // Write Your logic

     } else {        
     // Process form file field (input type="file").     
     String fieldname = item.getFieldName();    
     String filename = FilenameUtils.getName(item.getName());
     InputStream filecontent = item.getInputStream();  
       // Write Your logic
     }
     }
     } catch (FileUploadException e) {
     throw new ServletException("Cannot parse multipart request.", e);
     }
     }
    By using Servlet 3.0 MultipartConfig
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Collection;
    import java.util.Enumeration;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.MultipartConfig;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.Part;
    @WebServlet(urlPatterns = "/MultipartUploadServlet", name = "MultipartUploadServlet")
    @MultipartConfig(location = "/tmp", maxFileSize = 10485760L)
    public class MultipartYourUploadServlet extends HttpServlet {
            protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                            throws ServletException, IOException {
                    try {
                            Enumeration<String> hn = req.getHeaderNames();
                            while (hn.hasMoreElements()) {
                                    String n = hn.nextElement();
                                    System.out.println(n + " [" + req.getHeader(n) + "]");
                            }
                            Collection<Part> requestParts = req.getParts();
                            InputStream is = req.getInputStream();
                            int charRead = 0;
                            System.out.println("[");
                            while ((charRead = is.read()) != -1) {
                                    System.out.print((char) charRead);
                            }
                            is.close();
                            System.out.println("]");
                    } catch (Exception excp) {
                            excp.printStackTrace();
                    }
            }
    }

    22 )   How you make an AJAX call to Servlet and return the XML response

    Ans)
    We could make a AJAX call from browser using "XMLHttpRequest". The XMLHttpRequest
    object provide a method for exchanging data asynchronously between browser and
    server to avoid full page reloads.
    Here is the quick example:
                 function makeAjaxCall(){
                    if(window.XMLHttpRequest){
                                    alert("XMLHttpRequest supported by browser ee");
                                    xhttp = new XMLHttpRequest();
                                            url='http://localhost:8080/test/post.do';
                                    xhttp.open("GET", url, false);
                                    alert("reching your Request ?");
                                    xhttp.send();

                            alert(xhttp.responseText);
                                }
                                if(window.ActiveXObject){
                                    alert("ActiveXObject supported by browser");
                                }
                 }

    23 )   How you read an Image with a Servlet ?

    Ans)
    Two important Steps  while reading an Image with a Servlet.
    i) Getting the MIME type and setting to Response .
     String mimeType = getServletContext().getMimeType(filename);
          res.setContentType(mimeType); 

    ii) Reading the Image in small chunks as follows
            byte[] buf = new byte[1024];
    public class ImageReader extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res)
                                    throws ServletException, IOException {
      
          FileInputStream fis = null;
          String filename  = "C:/Img/yourOwn.jpg";
          String mimeType = getServletContext().getMimeType(filename);
          if (mimeType == null) {
              sc.log("Could not get MIME type of "+filename);
              res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
              return;
           }

          res.setContentType(mimeType);
          
          ServletOutputStream output = res.getOutputStream();
          try {
            fis = new FileInputStream(new File(filename));
            byte[] buf = new byte[1024];
            int i = 0;
            while ((i = fis.read(buf)) != -1) {
                output.write(buf, 0, i);
            }
            output.flush();
          } finally {
              fis.close();
              output.close();
          }
         }
     }
    }

    24 )   What is JSP ?

    Ans)
    A JSP page is a text document that contains two types of text: static data, which can be expressed in any text-based format
    (such as HTML, SVG, WML, and XML), and JSP elements, which construct dynamic content
    <%out.println("test JSP");%>

    25 )   How you have Import Statements in JSP and What is Page Directive ?

    Ans)
    The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code
    page directives anywhere in your JSP page.
    By convention, page directives are coded at the top of the JSP page.
    You could have import statements in JSP by using "@page" as shown below.
    <%@ page import="java.util.*, java.lang.*" %>
    <%@ page buffer="5kb" autoFlush="false" %>
    <jsp:directive.page errorPage="error.jsp" />

    26 )   Implicit Objects in JSP ?

    Ans)
    There are nine implicit objects. Here is the list of all the implicit objects:
    Object                Class
    application          javax.servlet.ServletContext
    config                   javax.servlet.ServletConfig
    exception             java.lang.Throwable
    out                        javax.servlet.jsp.JspWriter
    page                    java.lang.Object
    PageContext     javax.servlet.jsp.PageContext
    request              javax.servlet.ServletRequest
    response          javax.servlet.ServletResponse
    session            javax.servlet.http.HttpSession

    27 )   How you forward the response of JSP to other JSP ?

    Ans)
    By using <jsp:> directive or using the Pagecontext.
    <jsp:forward page="error.jsp" />
    <%pageContext.forward("<some relative jsp>");%>

    28 )   How you would Include a JSP in another JSP ?

    Ans)
    <jsp:include page="foo.jsp"/>

    29 )   Can we send Parameters in JSP Forward and Include Tags ?

    Ans)
    You can pass the Parameters to JSP include/Forward as shown below
    <jsp:forward page="secondpage.jsp">
    <jsp:param name="parameter1_name" value="parameter1_value">
    <jsp:param name="parameter2_name" value="parameter2_value">
    ...
    </jsp:forward>

    30 )   What is a TAG library ?

    Ans)
    In the Java Server Pages Technology, multiple actions are accessed by using the tags of the JSP whether the tag is standard tag of the JSP or the custom tag that is made by you. Actions in JSP are created for using programming language objects and gives output as you wish.
    Tag libraries are declared by using the <%@taglib %> directive of the JSP, it should have three attributes including "uri, prifix, tagdir"
    <%@taglib prifix="c" uri="http://java.sun.com/jsp/jstl/core" %>

    31 )   Methods to be implemented in a tag Library ?

    Ans)
    Please take a look at sample cutomer tag below, this Custom tag extends TagSupport and implements "doStartTag()" and "doEndTag()" in which you write the Content that to be appeared when this Tag was rendered by your JSP compiler.
    public class Hello extends TagSupport {
            private String name=null;

            public String getName(){
                     }
        public int doStartTag() {
      
           JspWriter out = pageContext.getOut();
              return SKIP_BODY;
        }
        public int doEndTag(){
            }
    }

    32 )   What is JSTL ?

    Ans)
    The JSP Standard Tag Library (JSTL) is a collection of custom tag libraries that implement general-purpose functionality common to Web applications, including iteration and conditionalization, data
    management formatting, manipulation of XML, and database access.
    Please see the following, we could use the JSTL "c:out" tag to print the content in your JSP .
    <c:out value="${user.firstName}"/>

    Choose tag looks like below.
    <c:choose><c:when test="${user.role == 'member'}">
        <p>Welcome, member!</p>
      </c:when><c:otherwise>
        <p>Welcome, guest!</p>
      </c:otherwise></c:choose>

    33 )   What is JSP Compilation ?

    Ans)
    When you access your JSP for the first , that Jsp Compiler (Web Container) will create an assosiated "Java Servlet
    Class", compile it and create a .class file
    , this process is called Jsp compilation.
    As a result your JSP pages take more time to load during their first request. These JSPs will be re-compiled whenever
    there is a change in the content.

    34 )   What is JSP pre-compilation ? What is the advantage of this?

    Ans)
    Due to compilation JSPs load very slow when accessed first time and could be a Performance issue. So we could avoid this and improve the performance by doing pre-compilation the JSPs and create the classes and ship them as part of Build artifacts like  WAR file .
    This Pre-Compilation could be done different ways, most of the Application Servers have their own built in configuration TAGs to achieve this.
    For Weblogic, you should have this in weblogic.xml
    <jsp-param>
    <param-name>precompile</param-name>
    <param-value>true</param-value>

    </jsp-param>

    For doing this using ANT target, do the following, you have to use JASPER ant task.
    <target name="jspc">
    <jasper2
    validateXml="false"
    uriroot="${build.war.dir}"
    webXmlFragment="${build.war.dir}/WEB-INF/generated_web.xml"
    addWebXmlMappings="true"
    outputDir="${build.src.dir}" />

    </target>

    35 )   What is JNDI ?

    Ans)
    The Java Naming and Directory Interface (JNDI) is an application programming interface
    (API) for accessing different kinds of naming and directory services. JNDI is not
    specific to a particular naming or directory service, it can be used to access many
     different kinds of systems including file systems; distributed objects systems
     like CORBA, Java RMI, and EJB; and directory services like LDAP, Novell NetWare, and NIS+.
    JNDI is similar to JDBC in that they are both Object-Oriented Java APIs that
     provide a common abstraction for accessing services from different vendors.
     While JDBC can be used to access a variety of relational databases,
     JNDI can be used to access a variety of of naming and directory services.
    Weblogic JNDI Look Up:
    Two steps , get obtain the InitialContext(), lookup() or Register by using Bind();
    Context ctx = null;
    Hashtable ht = new Hashtable();
    ht.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory");
    ht.put(Context.PROVIDER_URL,
    "t3://localhost:7001");
    try {
    ctx = new InitialContext(ht);
    ctx.bind("my_object", MyObect);
    ServiceBean bean = (ServiceBean)ctx.lookup("ejb.serviceBean");
    }
    catch (NamingException e) {
    // a failure occurred
    }
    Spring JNDI tag:
       <bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
            <property name="environment">
                <props>
                    <prop key="java.naming.factory.initial">
        com.sun.jndi.fscontext.RefFSContextFactory</prop>
                    <prop key="java.naming.provider.url">file:c:/temp</prop>
                </props>
            </property>
        </bean>
        <bean id="jndiDataSource" class="
     org.springframework.jndi.JndiObjectFactoryBean">
            <property name="jndiTemplate">
              <ref bean="jndiTemplate"/>
            </property>
            <property name="jndiName">
                  <value>MYCONNECTIONKEY</value>
            </property>
          </bean>

    Web Sphere JNDI :
     Properties p = new Properties();
     p.put("org.omg.CORBA.ORBClass","com.sun.CORBA.iiop.ORB");
        p.setProperty( javax.naming.Context.INITIAL_CONTEXT_FACTORY,
        "com.ibm.websphere.naming.WsnInitialContextFactory" );
        p.setProperty( "java.naming.provider.url", "iiop://HOSTNAME:PORT" );

        String connectionfactoryjndi="jms/testQCF";
        String sendQueueName="jms/destOutboundQ";
        Context jndiContext = new InitialContext();
        jndiContext = new InitialContext( p );

    36 )   What is JMS ? (MOM)

    Ans)
    Java Message Service (JMS) is an application program interface (API) from Sun Microsystems that supports the formal
    communication known as messaging between computers in a network
    . Sun's JMS provides a common interface to standard
    messaging protocols 
    and also to special messaging services in support of Java programs.
    Using the JMS interface, a programmer can invoke the messaging services of IBM's MQSeries, Progress Software's SonicMQ,
    ActiveMQ and other popular messaging product vendors. In addition, JMS supports messages that contain serialized Java
    objects and messages that contain Extensible Markup Language (XML) pages.

    37 )   What are the Messaging Models JMS ?

    Ans)

    • Messaging Models JMS
    The JMS API supports two models:
    Point-to-point
      The Point-to-point supports queueing the messages , could be consumed by only one client.





    Publish and subscribe
       The publish/subscribe model supports publishing messages to a particular message topic




    38 )   JMS Topic VS Queue ?


    Ans)

    QueueTopic
     Follows “Point-to-point ”  ModelFollows “Publish and subscribe” Model.
    Only One Consumer (Client) could read the message.Zero or more consumers will receive the message.
    Given Message would be available in Queue until that is read by a Client.There is a timing dependency between publishers and subscribers. The publisher has to create a message topic for clients to subscribe. The subscriber has to remain continuously active to receive messages, unless it has established a durable subscription.
    With a “Queue Browser”  you could browse (View) the messages that are in Queue, but can’t consume , messages will remain in Queue even after browsing through Queue Browser.          


    39 )   What is the JMSSession ?

    Ans)
    A Session object is a single-threaded context for producing and consuming messages. Although it may allocate provider
    resources outside the Java virtual machine (JVM), it is considered a lightweight JMS object.A JMS session can be
    nontransacted, locally transacted, or participating in a distributed transaction.
    javax.jms.Session qSession = qConnection.createSession(false,Session.AUTO_ACKNOWLEDGE);

    40 )   What is Message Browsing ?

    Ans)
    "QueueBrowser" would allow you to browse the message from a Queue (just viewing), this would not delete the messages
    from that Queue, where are when a Reciever (Consumer) reads the Message from a Queue that would no longer be available
    in Queue.

    41 )   What is the Temporary Queue/Topic?

    Ans)
    A TemporaryQueue is a Queue created within a QueueSession and exists for the lifetime of the QueueSession, no
    configuration required for creating a TempararyQueue.
    javax.jms.Session tSession = tConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    javax.jms.Queue replyQueue = qSession.createTemporaryQueue();

    42 )   What is the JMS What is the JMS correlation id ?

    Ans)

    • JMS Request Response example
      Sample Img 42

    import javax.jms.Connection;
    import javax.jms.Destination;
    import javax.jms.JMSException;
    import javax.jms.Message;
    import javax.jms.MessageConsumer;
    import javax.jms.MessageProducer;
    import javax.jms.Session;
    import javax.jms.TextMessage;
    import javax.naming.NamingException;
    public class ReplyResponseExample {
     private Session session;
     private Destination replyQueue;
     private MessageProducer requestProducer;
     private MessageConsumer replyConsumer;
     private MessageProducer invalidProducer;
     protected Requestor() {
      super();
     }
     public static Requestor newRequestor(Connection connection, String requestQueueName,
      String replyQueueName, String invalidQueueName)
      throws JMSException, NamingException {

      Requestor requestor = new Requestor();
      requestor.initialize(connection, requestQueueName, replyQueueName, invalidQueueName);
      return requestor;
     }
     protected void initialize(Connection connection, String requestQueueName,
      String replyQueueName, String invalidQueueName)
      throws NamingException, JMSException {

      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

      Destination requestQueue = JndiUtil.getDestination(requestQueueName);
      replyQueue = JndiUtil.getDestination(replyQueueName);
      Destination invalidQueue = JndiUtil.getDestination(invalidQueueName);

      requestProducer = session.createProducer(requestQueue);
      replyConsumer = session.createConsumer(replyQueue);
      invalidProducer = session.createProducer(invalidQueue);
     }
     public void send() throws JMSException {
      TextMessage requestMessage = session.createTextMessage();
      requestMessage.setText("Hello world.");
      requestMessage.setJMSReplyTo(replyQueue);
      requestProducer.send(requestMessage);
      System.out.println("Sent request");
      System.out.println("\tTime:       " + System.currentTimeMillis() + " ms");
      System.out.println("\tMessage ID: " + requestMessage.getJMSMessageID());
      System.out.println("\tCorrel. ID: " + requestMessage.getJMSCorrelationID());
      System.out.println("\tReply to:   " + requestMessage.getJMSReplyTo());
      System.out.println("\tContents:   " + requestMessage.getText());
     }
     public void receiveSync() throws JMSException {
      Message msg = replyConsumer.receive();
      if (msg instanceof TextMessage) {
       TextMessage replyMessage = (TextMessage) msg;
       System.out.println("Received reply ");
       System.out.println("\tTime:       " + System.currentTimeMillis() + " ms");
       System.out.println("\tMessage ID: " + replyMessage.getJMSMessageID());
       System.out.println("\tCorrel. ID: " + replyMessage.getJMSCorrelationID());
       System.out.println("\tReply to:   " + replyMessage.getJMSReplyTo());
       System.out.println("\tContents:   " + replyMessage.getText());
      }
     }
    }

    43 )   What is RMI ?

    Ans)
    Remote Method Invocation (RMI) facilitates object function calls between Java Virtual Machines (JVMs). JVMs can be
    located on separate computers - yet one JVM can invoke methods belonging to an object stored in another JVM.

    One Con with RMI is this could be used to communicate between two JVMs only could not work with other Heterogeneous
    Systems.
    public interface PowerService extends java.rmi.Remote
    {
    public void calculateTax(Double amount);
    }

    44 )   RMI vs CORBA ?

    Ans)
    RMI uses Java Remote Method Protocol (JRMP) to communicate with other distributed systems, so this is easy to integrate
    all Java based systems
    , but if you want to integrate your System with other Heterogeneous Systems which are based on other
    languages C, C++,.NET you need to either use JNI or create some adapters which is touch to implement and maintain.

    CORBA uses IIOP protocal and could allow to integrate your System with any other Systems based on other Languages like
    C,C++. But implementation CORBA is a little touch.

    So if you have all Java Based systems use RMI , if not use CORBA

    45 )   What is EJB ? How many kinds of EJBs available ?

    Ans)
    Enterprise JavaBeans (EJB) is a managed, server-side component architecture for modular construction of enterprise applications.

    There are three types of Enterprise Java Beans namely:
    i)Session Beans
    ii)Entity Beans
    iii)Message driven beans

    46 )   Describe SessionBean, EntityBean, Message Driven beans ?

    Ans)
    1) Session Beans
     Session beans are intended to allow the application author to easily implement portions of application code in middleware
     and to simplify access to this code.

    Session beans are divided into two types:
    a)     Stateless Session Bean
    b)     State full Session Bean
           a)    Stateless Session Bean
                   A stateless session bean does not maintain a conversational state with the client. When a client invokes
                   the methods of a stateless bean, the bean’s instance variables may contain a state specific to that client,
                   but only for the duration of the invocation. When the method is finished, the client-specific state
                   should not be retained.
            b)    State full Session Bean
                    The state of an object consists of the values of its instance variables. In a stateful session bean, the
                    instance variables represent the state of a unique client-bean session. Because the client interacts (“talks”)
                    with its bean, this state is often called the conversational state. The state is retained for the duration of
                    the client-bean session.
    2) Entity Beans
    An entity bean represents a business object in a persistent storage mechanism. Some examples of business objects are
    customers, orders, and products. In the J2EE SDK, the persistent storage mechanism is a relational database.

    3) Message driven beans
    A message-driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously. It acts as a
    JMS message listener, which is similar to an event listener except that it receives messages instead of events.

    47 )   What is SessionBean pool ?

    Ans)
    Stateless session beans do not maintain any State between two client calls, each client call is to be considered as a new one. To avoid the Bean creation and start up overhead, EJB container creates a Pool of stateless SessionBeans which are in ready to serve state, this could be helpful in several ways.
    • One, by having one bean per instance, you're guaranteed to be threads safe (Servlets, for example, are not thread safe)
    • Two, you reduce any potential startup time that a bean might have.
    • Three, you can use bean pool as a means to throttle traffic. If you only have 10 Beans in a pool, you're only going to get at most 10 requests working simultaneously, the rest will be queued up.

    48 )   Life Cycles of EJBs ?

    Ans)

    • EJBs Life Cycles
      Sample Img 48
    Stateless Session Bean
               A stateless session bean has only two states: Does Not Exists and Method Ready Pool.
        
         Stateful Session Bean
               Unlike Stateless, a Stateful Session Bean has three states. Does not exists, Method Ready and Passivated states.
          Life Cycle of an Entity Bean 
                An Entity Bean could have three states, Does not exists, Pooled and Ready
          Life Cycle of a Message Driven Bean
                 A Message Driven Bean has two states, Does not exists, Ready

    49 )   What is a Transaction ?

    Ans)
    A transaction is a single Unit Of Work, composed of one or more steps.

       In the real world,  a Transaction represents an exchange between two entities . When you order a book online,
       you place order for the book, the book is removed from inventory,
       your credit card is processed, the book is shipped , and you receive it.

    50 )   CMT VS BMT beans ?

    Ans)
    CTMBTM
    Container will take the responsibility of managing the Transactions based on the Transaction Attribute you provided in EJB xml or as an annotation , as shown below.
    @TransactionAttribute(value=REQUIRES_NEW)
    When you use bean-managed transactions (BMT), the bean-provider is responsible for ensuring that a transaction is started and committed when appropriate.
    All session and message-driven beans may use CMT.

    EJB 2.1 entity beans must use CMT.
    EJB 3.0 entities cannot be configured with a transaction management type. EJB 3.0 entities execute within the transactional context of the caller.
    Only session and message-driven beans may use BMT.
    Entity Beans can’t use BMT.


    51 )   What is ACID ?

    Ans)
    Transactions Exhibit four main Characterstics : Automicity , Consistency, Isolation, and Durability .
    Automicity
    Automicity implies that a Transaction will be treated as a single unit of work, as we discussed above ,
    a Transaction could have several steps , all these should be considered as Single unit and the Transaction
    would be either successful (COMITT)  or failed (ROLLBACK), should not have any partial comitts. When each step of
    the transaction is completed successfully then that Transaction would be considered as Success (COMITT),
    if any single step failure could mark entire Transaction as Failed (ROLLBACK).
    Consistency
    Consistency guarantees that the Transaction will leave the system and data in consistent state.We say the data is in
    consistent state when it adheres to the Constaints , or Rules, of the Database.
    Isolation 
    Isolation guarantees , the data that a transaction accesses will not be affected by any other changes made by other
    Transactions until the First transaction completes.
    Durability
    The Durabilty property specifies that when a transaction is comitted , any changes to data that it made should be persisted
    to a permanent storage.

    52 )   What is a Nested Transaction ?

    Ans)
    A nested transaction is used to provide the transactional guarantee for a subset of operations that
    performed in a larger transaction, this would allow you to comitt or abort the subset of operations
    independently of the larger transaction. 
    Committing a nested transaction has no effect on the state of the parent transaction. The parent
    transaction is still uncommitted. However, the parent transaction can now see any modifications made
    by the child transaction. Those modifications, of course, are still hidden to all other transactions
    until the parent also commits.
    // parent transaction
     Transaction parentTxn = myEnv.beginTransaction(null, null);
    // child transaction
    Transaction childTxn = myEnv.beginTransaction(parentTxn, null);

    53 )   CMT Transaction Attributes ?

    Ans)


      Transaction AttributeClient-Controlled Transaction ExistsClient-Controlled Transaction Does Not Exist
      Not SupportedContainer suspends the client transaction Use no transaction
      SupportsUse client-controlled transaction Use no transaction
      RequiredUse client-controlled transaction Container starts a new transaction
      Requires NewContainer suspends the client transaction and starts a new transactionContainer starts a new transaction
      Mandatory Use client-controlled transaction Exception raised
      NeverException raisedUse no transaction

       In EBJ 3.0 you
                      @Stateful
                      @TransactionManagement(value=TransactionManagementType.CONTAINER)
                      @TransactionAttribute(value=REQUIRED)
                      public class CartBean implements Cart {
                          private ArrayList items;
                          @PostConstruct
                          public void initialize() {
                              items = new ArrayList();
                          }
                          @Remove
                          @TransactionAttribute(value=REQUIRES_NEW)
                          public void finishedShipping() {
                              // Release any resources.
                          }
                          public void addItem(String item) {
                              items.add(item);
                          }
                          public void removeItem(String item) {
                              items.remove(item);
                          }
                      }

      54 )   What is the Role of the EJB Container in EJBs ?

      Ans)
      An Enterprise JavaBeans (EJB) container provides a run-time environment for enterprise beans
      within the application server. The container handles all aspects of an enterprise bean's
      operation within the application server and acts as an intermediary between the user-written
      business logic within the bean and the rest of the application server environment
      The EJB container provides many services to the enterprise bean, including the following:
      i) Beginning, committing, and rolling back transactions as necessary.
      ii) Maintaining pools of enterprise bean instances ready for incoming requests and moving these
      instances between the inactive pools and an active state, ensuring that threading conditions
      within the bean are satisfied.
      iii) Most importantly, automatically synchronizing data in an entity bean's instance variables with
      corresponding data items stored in persistent storage.

      55 )   How you declare a Transaction for a given Business Method in a given SessionBean ?

      Ans)
      <?xml version="1.0" encoding="UTF-8"?> 
      <enterprise-beans> 
        <session> 
          <ejb-name>Hello</ejb-name> 
          <home>hello.HelloHome</home> 
          <remote>hello.Hello</remote> 
          <ejb-class>hello.HelloBean</ejb-class> 
          <session-type>Stateless</session-type> 
          <transaction-type>Container</transaction-type> 
        </session> 
      </enterprise-beans>

      56 )   What are transaction isolation levels in EJB?

      Ans)
      i) Transaction_read_uncommitted- Allows a method to read uncommitted data from a DB(fast but
      not wise).
      ii) Transaction_read_committed- Guarantees that the data you are getting has been committed.
      iii) Transaction_repeatable_read - Guarantees that all reads of the database will be the same during
      the transaction (good for read and update operations).
      iv) Transaction_serializable- All the transactions for resource are performed serial.

      57 )   How could you manage State in EJB layer ?

      Ans)
      We manage state in EJB layer is by using "StatefulSessionBean".

      58 )    If you have Business Layer (EJB layer) which could be accessed by a web application as well as a Standalone application , how could you manange state which used by both the applications ?

      Ans)
      You have to create StatefulSessionBean and make that accessible for both Web as well as Standalone applications.
      You could access the Stateful Session by using  JNDI look up.
      From as Stanalone Client you could use application specific protocal to connect to JNDI tree.
      Weblogic:
      Properties p = new Properties();
      p.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
      String url = "t3://localhost:7001";
      p.put(Context.PROVIDER_URL, url);
      Context ctx = new InitialContext(p);
      MyBeanHome home = (MyBeanHome)ctx.lookup("server.MyBeanHome");
      MyBean remote = home.create();
      WebSphere:
      1)
       Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                        "com.ibm.websphere.naming.WsnInitialContextFactory");
           env.put(Context.PROVIDER_URL, "corbaloc::localhost:2809");
            InitialContext ctx = new InitialContext(env);

      2)
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY,
           "com.ibm.websphere.naming.WsnInitialContextFactory");
      env.put(Context.PROVIDER_URL, "iiop://myhost.mycompany.com:2809");
      Context initialContext = new InitialContext(env);

      59 )   What is EJB activation and Passivation ?

      Ans)
      Activation is a process of associating an instance with EJB object.Activating a bean is the
      process of restoring a stateful bean instance’s state relative to its EJB object. Whe
      n a method
      on the passivated EJB object is invoked, the container automatically creates a new instance and
      sets it fields equal to the data stored during passivation. The activation process is supported
      by the state management call methods ejbActivate ().
      Passivation is the process of disassociating a bean instance from its EJB object so that the
      instance can be reused or evicted to conserve memory. Ca
      lling of ejbPassivate () for passivation
      is a warning to the bean that its held conversational state is about to be swapped out. It is
      important that the container inform the bean using ejbPassivate () so that the bean can
      relinquish held resources.

      60 )   How you invoke a Session Bean from a Batch Job or a Standalone application ?

      Ans)

      You could access the Stateful Session by using  JNDI look up.
      From as Stanalone Client you could use application specific protocal to
      connect to JNDI tree.
      Weblogic:
      Properties p = new Properties();
      p.put(Context.INITIAL_CONTEXT_FACTORY,
       "weblogic.jndi.WLInitialContextFactory");
      String url = "t3://localhost:7001";
      p.put(Context.PROVIDER_URL, url);
      Context ctx = new InitialContext(p);
      MyBeanHome home = (MyBeanHome)ctx.lookup("server.MyBeanHome");
      MyBean remote = home.create();
      WebSphere:
      1)
       Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                 "com.ibm.websphere.naming.WsnInitialContextFactory");
           env.put(Context.PROVIDER_URL, "corbaloc::localhost:2809");
            InitialContext ctx = new InitialContext(env);

      2)
      Hashtable env = new Hashtable();
      env.put(Context.INITIAL_CONTEXT_FACTORY,
           "com.ibm.websphere.naming.WsnInitialContextFactory");
      env.put(Context.PROVIDER_URL, "iiop://myhost.mycompany.com:2809");
      Context initialContext = new InitialContext(env);

      61 )   What is MDB (Message Driven Bean ) ?

      Ans)
      A message-driven bean is an enterprise bean that allows J2EE applications to process messages
      asynchronously
      . It acts as a JMS message listener, which is similar to an event listener except
      that it receives messages instead of events.
      @MessageDriven(mappedName="jms/Queue")
        public class MessageBean implements MessageListener {
         @Resource
         private MessageDrivenContext mdc;

         public void onMessage(Message msg) {
           TextMessage tmsg = null;
         try {
         tmsg = (TextMessage) msg;

        } catch (JMSException e) {

         }
         public void ejbRemove( )throws EJBException{
         }
      }

      62 )   New on EJB 3.0

      Ans)

       Very high level the changes in the proposed EJB 3.0 specification can be divided into two categories:

      •An annotation-based EJB programming model, in addition to the EJB 2.1 model of defining
       an application's behavior through deployment descriptors and several interfaces.
      •The new persistence model for entity beans. EJB QL has also changed significantly.

      Stateless session beans:
      A stateless session bean (SLSB), written the EJB 3.0 way,
      i) Just a plain Java file with a class-level annotation of @Stateless,interface is not required.
      ii) The @Remote annotation can be used to indicate that a remote interface should be generated.
      import javax.ejb.*;

      @Stateless
      @Remote

      public class HelloWorldBean {
         public String sayHello() {
            return "Hello World!!!";
         }
      }

      Entity beans :
      i)
      Entity beans are marked with the @Entity annotation, and all properties/fields in
      the entity bean class not marked with the @Transient annotation are considered persistent.
      ii) JPA, the persistence API:
      Provides a standard for object-relational mapping (ORM).
      • It is not tied to the Java EE containter and can be tested and used with standard Java
      • A service provider interface so that the code can be developed independent of the database
      and other resources used.
      EntityManager manages the transactions and this is Injected by Container into SessionBean
      as shown below.
      @Stateless
      @Remote(Bank.class)
      public class BankBean implements Bank {
      /**
           * The entity manager object, injected by
              the container
           */
          @PersistenceContext
          private EntityManager manager;


      public List<Account> listAccounts() {
              Query query = manager.createQuery(
                                        “SELECT a FROM Account a”);
               return;
         }
      }

      63 )   What is new in EJB 3.1 ?

      Ans)
      Some of the new Features in Ejb 3.1 are below.
      i) EJB Interfaces are Optional
      you do not need any interfaces for Session Beans, just like JPA Entities and Message
      Driven Beans. All you have to do is annotate a POJO with the @Stateless or @Stateful
      to get a fully functional EJB. Take a look at the example below.
      @Stateless
      public class PlaceBidBean {
      @PersistenceContext
       private EntityManager entityManager;
       public void placeBid (Bid bid) {
       entityManager.persist(bid);
       }
      }
      Expose Session Bean as Web service :
      @Stateless @WebService
      public class PlaceBidBean {

       @PersistenceContext
        private EntityManager entityManager;
        @WebMethod public void placeBid (Bid bid) {
        entityManager.persist(bid);
        }
      }
      Allows Singleton Beans :
      The following bean load data in init() method and saves the data when destroyed
      @Singleton
      public class YourTestBean {

       @PersistenceContext
       private EntityManager entityManager;
       private Rate rate;
       @PostConstruct
       private void init() {
       rate = entityManager.find(Rate.class, 1);
       }
       @PreDestroy
       private void destroy() {
       entityManager.merge(rate);
       }
       public void setRate(Rate rate) {
       this.rate = rate;
       }
       public Rate getRate() {
       return rate;
       }
      }

      iii)
      Support for direct use of EJBs in the servlet container, including simplified packaging
      options
      . The current thought is to allow EJBs in the WEB-INF/classes directory while
      allowing ejb-jar.xml to reside in the WEB-INF directory, just like the web.xml file.
      In a similar vein, you would be able to place an EJB jar into the WEB-INF/lib directory.
      iv) Support for stateful web services via Stateful Session Bean web service endpoints.

      64 )   If you want to make your application Clusterable ? What are considerations you need to take into account from EJB and JMS perspective ?

      Ans)

      • Making your application Clusterable.
        Sample Img 64
      When you want to make your application Clusterable, you have to first identify what are thing
      (which holds the State data)should be synchronized among all the Machines in the Cluster for
      supporting High avialblity Without impacting the application functionality.
      Here are the list of things you should look at.
      HTTP Session (Session Replication) :
           In a Clustered ENV, your application server keep the HttpSession state in Sync among all
        the Servers in Cluster, this could be by using different communication technique
        like IP MultiCast etc. So for better performance you have to do the following.

              i) Try to keep little data in HttpSession, do not keep pretty big Object graphs in
        HttpSession, becase each change to Session Data would triggers  session replication
        which serializes the Session state and transport that to all the Servers in cluster.
           ii) All the Objects stored in Session should be Seriazable , if not Session
         replication would be failed.
      Stateful session beans :
         You should take the same considetaions as above, even in StateFul Session Beans case.
      Singleton classes :
           By design as Singleton classes would be maintained as One Instance per JVM, so making
        a Singleton class Custable is a little Chanllenging as all the JVMs in any given Clusttered
        ENV would have their own Instance of Singleton classes.  So you have to manually keep
        the  One possible solution for this issue is below.

      i)  Serialize the First Instance of a singleton class and store in Database. Serialize the
          First Instance of a singleton class which is created on any JVM and store that in Database,
       let all other JVMs check in Database if a singleton class was already created before
       Creating their own Instance, this way we can make sure that the same Instance is being used
       by all the Servers.
      JMS Queues:
      You may need to use Distributed Queues or Topics.

      65 )   Can we expose a SessionBean as a web service ?

      Ans)
      Yes, you can.
      Please take a look at example of  a  Stateless Sessionbean  exposed as a Web Service.
      import java.rmi.RemoteException;
      import java.util.Properties;
      import javax.ejb.Stateless;

      /**
      * This is a session bean class
      */
      @Stateless(name="HelloServiceEJB")
      public class HelloServiceBean implements HelloServiceInf {
          public String sayHello(String name) {
              return("Hello "+name +" a Web Service");
          }
      }

      66 )   Websphere Message Queue Example .

      Ans)
      import java.util.Properties;
      import javax.jms.JMSException;
      import javax.jms.Queue;
      import javax.jms.QueueConnection;
      import javax.jms.QueueConnectionFactory;
      import javax.jms.QueueReceiver;
      import javax.jms.QueueSender;
      import javax.jms.QueueSession;
      import javax.jms.Session;
      import javax.naming.Context;
      import javax.naming.InitialContext;
      public class TestMQ {
              public static void main(String[] args) {
                      try {
                              Properties p = new Properties();
                          p.put("org.omg.CORBA.ORBClass","com.sun.CORBA.iiop.ORB");
                          //p.put("org.omg.CORBA.ORBSingletonClass","com.ibm.rmi.corba.ORBSingleton");
                         // p.put("javax.rmi.CORBA.UtilClass","com.ibm.rmi.javax.rmi.CORBA.Util");
                        //  p.put("javax.rmi.CORBA.StubClass","com.ibm.rmi.javax.rmi.CORBA.StubDelegateImpl");
                         // p.put("java.naming.factory.url.pkgs","com.ibm.ws.naming");
                              p.setProperty( javax.naming.Context.INITIAL_CONTEXT_FACTORY,
                              "com.ibm.websphere.naming.WsnInitialContextFactory" );
                              //javax.naming.Context.INITIAL_CONTEXT_FACTORY, for the property name,
                              //and the constant, com.ibm.websphere.naming.PROPS.INITIAL_CONTEXT_FACTORY, for the property value.
                              p.setProperty( "java.naming.provider.url", "iiop://HOSTNAME:PORT" );
                      
                              String connectionfactoryjndi="jms/testQCF";
                              //String sendQueueName="jms/apinboundq";
                              String sendQueueName="jms/destOutboundQ";
              
                              Context jndiContext = new InitialContext();
                              jndiContext = new InitialContext( p );
                              QueueConnectionFactory cf = (QueueConnectionFactory) jndiContext.lookup(connectionfactoryjndi);
                              System.out.println("Looked up : QueueConnectionFactory "+ connectionfactoryjndi);
                              System.out.println("Transport Queue [" + sendQueueName + "]");
                              QueueConnection connection = (QueueConnection) cf.createQueueConnection();
                              QueueSession session = (QueueSession) connection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
                              Queue queue = (Queue) jndiContext.lookup(sendQueueName);
                              QueueSender sender =  (QueueSender) session.createSender(queue);
                              QueueReceiver receiver = (QueueReceiver) session.createReceiver(queue);   
                              long uniqueNumber = System.currentTimeMillis() % 1000;
                              javax.jms.TextMessage message =  session.createTextMessage("Test Message "+ uniqueNumber);  
                              // Start the connection
                              connection.start();
                              sender.send(message);
                      //      System.out.println("Sent message:\\n" + message);

                              sender.close();
                              receiver.close();
                              session.close();
                              connection.close();
                              System.out.println("\\nSUCCESS\\n");
                      }
                      catch (JMSException jmsex) {
                              System.out.println(jmsex);
                              System.out.println("\\nFAILURE\\n");
                      }
                      catch (Exception ex) {
                              System.out.println(ex);
                              System.out.println("\\nFAILURE\\n");
                      }
              }
      }


      Q)  Java File Download Servlet


      Ans)
      Servlet  - Excel Sheet - DownLoads Data as excel Sheet. 
      This Example shows how to download Data as a Excel sheet By Using Java POI.
      Step 1 :
      Create a FileDownloadServlet.java
      -------------------------------------------
      import java.io.IOException;
      import javax.servlet.ServletException;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;

      public class FileDownloadServlet extends HttpServlet {

            private static final long serialVersionUID = 8305367618713715640L;

        
            @Override
            protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                    throws ServletException, IOException {
                super.doGet(req, resp);
            }

            @Override
            protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {      
          
                   try {
                    DownloadHandler downloadHandler = new DownloadHandler(req,resp);
               String Result = downloadHandler.processAction();

                    } catch (Exception e) {
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"error occurred while processing: " + e.getMessage());
                    }
            }
        }

      Step 2 : 
      Implement DownloadHandler.java
      -------------------------------------------------------------------------------------
      import java.io.OutputStream;
      import java.util.ArrayList;
      import java.util.Collections;
      import java.util.Comparator;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import javax.servlet.http.HttpSession;
      import org.apache.poi.hssf.usermodel.HSSFRow;
      import org.apache.poi.hssf.usermodel.HSSFSheet;
      import org.apache.poi.hssf.usermodel.HSSFWorkbook;
      import com.comcast.commsales.trunking.client.model.CustomerDataVO;
      import com.comcast.commsales.trunking.client.model.validator.ValueValidator;
      import com.comcast.commsales.trunking.client.proxy.TrunkingService;

      public class DownloadHandler {
       HttpServletRequest req;
       HttpServletResponse resp;

       public DownloadHandlerImpl(){

       }
       public DownloadHandlerImpl(HttpServletRequest req, HttpServletResponse resp){
        this.req = req;
        this.resp = resp;

       }
       @SuppressWarnings("unchecked")
       public String processAction() throws Exception {
        OutputStream os = resp.getOutputStream();
        HttpSession session =  req.getSession();
              Boolean isTemplate = (Boolean)session.getAttribute("isTemplate");
              ArrayList<CustomerDataVO> CustomerDataVOList =  ( ArrayList<CustomerDataVO>)session.getAttribute("exportedCustomerData");
              session.removeAttribute("isTemplate"); //Remove the Session Attribute
              session.removeAttribute("exportedTFS"); //Remove the Session Attribute
           resp.setContentType("application/vnd.ms-excel");   
           String displayname="tollFree.xls";
           resp.setHeader("Content-Disposition","inline; filename=\"" + displayname + "\"");
        try{
             HSSFWorkbook wb = new HSSFWorkbook();
                HSSFSheet sheet = wb.createSheet("Excel Sheet");
                HSSFRow rowhead = sheet.createRow((short) 0);
                rowhead.createCell((short) 0).setCellValue("Customer FistName");
                rowhead.createCell((short) 1).setCellValue("Customer LastName");
            
                if(isTemplate != null && !isTemplate.booleanValue()){
                 int index = 1;
                 for(CustomerDataVO vo : customerDataVOList){
                  HSSFRow row1 = sheet.createRow((short) index);
                        row1.createCell((short) 0).setCellValue(vo.getFirstName());
                        row1.createCell((short) 1).setCellValue(vo.getLastName());
                  index++;
                 }
             }else{
              HSSFRow row1 = sheet.createRow((short)1);
                    row1.createCell((short) 0).setCellValue("xxxxxxxx");
                    row1.createCell((short) 1).setCellValue("xxxxxxxx");
                    HSSFRow row2 = sheet.createRow((short) 2);
                    row2.createCell((short) 0).setCellValue("Required");
                    row2.createCell((short) 1).setCellValue("Required");
             }

               wb.write(os);
        }catch(Exception e){
        }finally{
         os.flush();
         os.close();
         resp.flushBuffer();
        }
        return "";
       }
      }