Java Servlet to MSMQ Example

Summary

In this example you will learn how to use J-Integra® to access a public queue using Microsoft Message Queue System (MSMQ) from a Java Servlet on your local machine using only Java classes to access the created message queue.

Introduction

Accessing MSMQ on a remote or local machine from a Java Servlet can be extremely difficult for Java programmers. J-Integra® makes this easy by providing Java proxies that enable you to access all MSMQ methods with no knowledge of COM or DCOM.

Java Servlets running inside any Web Server that supports a standard JVM are able to use J-Integra® to read and write message to your existing MSMQ system and so to other applications within your network The Web Server can itself of course be running on any platform and your message queue can be running on any Windows machine that you can access over the network and can use public and private queues.

Prerequisites

  1. You should be familiar with Java Servlets and be able to install and configure your web server for access to the sample Java Servlet.

  2. Download and install J-Integra®. On this example we assume you have installed it under c:\jintegra.

  3. Make sure the jintegra.jar is included in your CLASSPATH environment variable.

  4. Ensure that you have installed the J-Integra® license.

  5. Download and install the JDK 1.2.x or higher.

  6. Read the Java™ Servlet to COM JSP/Servlet to Excel Example, since it introduces some basic concepts that are assumed here.

  7. You should have the Microsoft Message Queue (MSMQ) application installed on your system and have access to a Domain Controller for Active Directory setup.
  8. This example assumes you are using Windows 2000.

The Steps Involved

  1. Generate the Java proxies for MMSQ using J-Integra®

  2. Copy the Java Servlet code, compile and copy the proxy class files to the web server

  3. Deploy the example
  4. Run the example

  5. Remote Access

Generate the Java proxies for MMSQ using J-Integra®

  1. Create a sub-directory in the target directory and call this sub-directory simplemsmq
    Note:
    the name is case sensitive
  2. Run the J-Integra® com2java tool to generate the proxies for MQOA.dll.
  3. Enter the target directory just created into the Output Dir field
  4. Enter simplemsmq into the Java Package field
    Note:The sample Java Servlet should reside in a parent directory of the simplemsmq directory.

Copy the Java Servlet code, compile and copy the proxy class files to the web server

  1. Copy the following code in a file and call it "MsmqExample.java". This file is included in your jintegra\examples\servlet-com\ServletToMsMq directory when you download J-Integra®.

  2. import java.io.*; 
    import java.text.*; 
    import java.util.*; 
    import javax.servlet.*; 
    import javax.servlet.http.*; 
     
    import simplemsmq.*; 
     
    public class MsmqExample extends HttpServlet { 
      public void doGet(HttpServletRequest request, 
                        HttpServletResponse response) throws IOException, ServletException { 
        PrintWriter out = response.getWriter(); 
        String queueName = "\\sendtest1"; 
        MSMQQueueInfo qinfo = null; 
        try { 
          response.setContentType("text/html"); 
          out.println("<html>"); 
          out.println("<head>"); 
          out.println("<title>"); 
          out.println("Demonstration of Simple Java to MSMQ"); 
          out.println("</title>"); 
          // p1 is the number of messages, p2 is the message 
          String p1 = request.getParameter("v1"); 
          String p2 = request.getParameter("v2"); 
          // v1 is the number of messages to add to the queue 
          Integer v1 = null; 
          boolean badValues = false; 
          // try and format the user input 
          try { 
            v1 = p1 == null ? null : new Integer(p1); 
          } catch (NumberFormatException nfe) { 
            badValues = true; 
          } 
          // See if we need to ask for data input or illegal values entered 
          if (p1 == null || p2 == null || badValues || 
              !(v1.intValue() > 0 && v1.intValue() < 1000)) { 
            // Build a form asking for the number and message text 
            out.println("<body>Uses MSMQ to write and read a number of messages" + 
                        " to and from the queue"); 
            out.println("<form>Enter your two values and then click submit"); 
            out.println("<br>Number of messages (1-999) <INPUT NAME=v1 VALUE=\"10\" SIZE=3>" + 
                        "<br>The message <INPUT NAME=v2 SIZE=60><br><br><INPUT TYPE=SUBMIT>" + 
                        "</form></body></html>"); 
            return; 
          } 
          com.linar.jintegra.Cleaner.trackObjectsInCurrentThread(); 
          // Change this line for your appropriate Domain, UserName and Password 
          // Note that you can also allow J-Integra® to authenticate the current user 
          // (windows only) by ensuring that your Jintegra/bin directory is on your path. 
          // path. 
          com.linar.jintegra.AuthInfo.setDefault("Domain", "username", "password"); 
          // Create the queue on a remote machinee using its IP address
          // qinfo = new MSMQQueueInfo(123.456.7.89); 
          // Create the queue on a local machinee
          qinfo = new MSMQQueueInfo(); 
          // Look for a queue with the same name we will use, abort if one is found 
          MSMQQuery query = new MSMQQuery(); 
          IMSMQQueueInfos queryInfos = query.lookupQueue(null, null, null, null, null, null, null, null, null); 
          if (queryInfos != null) { 
            IMSMQQueueInfo queryInfo = queryInfos.next(); 
            while (queryInfo != null) { 
              if (queryInfo.getPathName().endsWith(queueName)) { 
                throw new Exception("Queue \"" + 
                                    queryInfo.getPathName() + "\" already exists. Please delete" + 
                                    " to prevent an error on creation.<br>"); 
              } 
              queryInfo = queryInfos.next(); 
            } 
          } 
          // This call will fail if the queue already exists. The queue should be 
          // deleted prior to running this servlet 
          qinfo.setPathName("." + queueName); 
          qinfo.create(null, null); 
          // Open the queue, and send a message 
          IMSMQQueue q = qinfo.open(MQACCESS.MQ_SEND_ACCESS, MQSHARE.MQ_DENY_NONE); 
          IMSMQMessage msg = new MSMQMessage(); 
          for (int message = 0; message < v1.intValue(); message++) { 
            msg.setLabel("Test Message " + message); 
            msg.setBody(p2); 
            msg.setPriority(5); 
            msg.send(q, null); 
          } 
          q.close(); 
          // Open the queue, and read the messages 
          q = qinfo.open(MQACCESS.MQ_RECEIVE_ACCESS, MQSHARE.MQ_DENY_NONE); 
          out.println("Your test message is \"" + p2); 
          out.println("\", you sent it " + p1 + " times to the queue, \"" + 
                      qinfo.getPathName() + "\""); 
          out.println("<br><br>Dumping sample queue properties ... "); 
          out.println("<br>Create Time= " + qinfo.getCreateTime()); 
          String isTransactional = null; 
          switch (qinfo.getIsTransactional()) { 
            case MQTRANSACTIONAL.MQ_TRANSACTIONAL_NONE: 
              isTransactional = "MQ_TRANSACTIONAL_NONE"; 
              break; 
            case MQTRANSACTIONAL.MQ_TRANSACTIONAL: 
              isTransactional = "MQ_TRANSACTIONAL"; 
              break; 
            default: 
              isTransactional = "NOTRECOGNIZED!"; 
              break; 
          } 
          String privLevel = null; 
          switch (qinfo.getPrivLevel()) { 
            case MQPRIVLEVEL.MQ_PRIV_LEVEL_NONE: 
              privLevel = "MQ_PRIV_LEVEL_NONE"; 
              break; 
            case MQPRIVLEVEL.MQ_PRIV_LEVEL_OPTIONAL: 
              privLevel = "MQ_PRIV_LEVEL_OPTIONAL"; 
              break; 
            case MQPRIVLEVEL.MQ_PRIV_LEVEL_BODY: 
              privLevel = "MQ_PRIV_LEVEL_BODY"; 
              break; 
            default: 
              privLevel = "NOTRECOGNIZED!"; 
              break; 
          } 
          // Show some info about the queue 
          out.println("<br>Transactional= " + isTransactional); 
          out.println("<br>Priv Level= " + privLevel); 
          out.println("<br>Priority Level= " + qinfo.getBasePriority()); 
          out.println("<br>"); 
          out.println("<br>Dumping all queue messages ... <br>"); 
          // Dump all messages on the queue 
          for (int message = 0; message < v1.intValue(); message++) { 
            msg = q.receive(null, null, null, null); 
            out.println("Message " + message + "= \"" + 
                        msg.getBody() + "\"" + "<br>"); 
          } 
          q.close(); 
          out.println("</head>"); 
          out.println("<body bgcolor=\"white\">"); 
          out.println("</body>"); 
        } catch (Exception e) { 
          PrintWriter pw = new PrintWriter(out); 
          e.printStackTrace(pw); 
          pw.flush(); 
        } finally { 
          if (qinfo != null) { 
            try { 
              qinfo.delete(); 
            } catch (Exception e) { 
              //Ignore exception, not important at this stage 
            } 
          } 
          com.linar.jintegra.Cleaner.releaseAllInCurrentThread(); 
        } 
      } 
    }

  3. Compile "MsmqExample.java" along with the J-Integra® generated proxies using your java development tool or using the JDK javac tool on command line. (Remember that you will need to have servlet.jar and jintegra.jar to compile the sample Java Servlet and J-Integra® proxy source files).

  4. In order to have access to a DCOM object, you need to be authenticated. Please see Security/Authentication for information on authentication and security.

  5. Copy the generated MsmqExample.class file and all the J-Integra® Java proxy classes in the simplemsmq directory to your chosen Servlet installation directory for your installed Web server.

Deploying the Example

For information on deploying your servlet or JSP to your Java Application Server, see the following procedures.

Deploying Servlets

Deploying Servlets to J2EE

Deploying Servlets to JRun

Deploying Servlets to TomCat

Deploying Servlets to WebSphere

Deploying JSPs

Deploying JSPs to J2EE

Deploying JSPs to JRun

Deploying JSPs to TomCat

Deploying JSPs to WebSphere

Run the example

  1. Depending on your Web server configuration, you may need to change the path to the MsmqExample. You should see a page that asks for the Number of messages and The message.

  2. Enter two values and click Submit Query, and you should see a response of the sample queue properties.

  3. Now check the messages in the queue. Right-click the My Computer icon on your desktop and click Manage. In the Computer Management dialogue box, double-click Services and Applications, then double-click Message Queuing. While the Servlet is writing and reading the message to the queue, right-click Public Queue and select Refresh. Remember that the queue is deleted after the last message is read, so you need to work fast. You should see a list of the messages being written.

Remote Access

When running under Windows, J-Integra® can use native code to pick up your current login identity. If you would rather that J-Integra® did not do this, or if you are not logged in to an NT domain (for example if your Java code is on a UNIX box), then you must configure DCOM access to MSMQ, and you must specify the NT domain, user and password to be used by the J-Integra® runtime.

Proceed to Configuring DCOM for Remote Access

Conclusion

Using J-Integra® you have enabled a Java Servlet to create an instance of a public queue on your local machine using MSMQ. A number of messages have been written and read to and from the queue using your Servlet.

Although this is a very trivial example, it demonstrates the power of the J-Integra®. Remember that you can access message queues on your local or remote Windows computer or access a remote MSMQ from a non-Windows computer