Sunday, February 6, 2011

JBOSS JMS

JBOSS JMS,
1. Place the attached file in source code of eclipse
2. Download Place the jars from jboss 5.0.4GA into build path. Place all the jars.
3. In default/conf/destination.xml under the Jboss folder add the mbean corresponding to queue..in our case testqueue
4. Start jboss. Should see the queue 5  Run the below program..

ChapterExRepositor.java

package jms;

import java.io.InputStream;
import java.io.IOException;
import java.net.URL;

import org.apache.log4j.Hierarchy;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.spi.RepositorySelector;
import org.apache.log4j.spi.LoggerRepository;
import org.apache.log4j.spi.RootCategory;
import org.apache.log4j.xml.DOMConfigurator;

/** An implementation of the Log4j RepositorySelector that looks for chapter
 * example local log4j.xml files
 * @author Scott.Stark@jboss.org
 * @version $Revision: 1.1 $
 */
public class ChapterExRepository implements RepositorySelector
{
   private static RepositorySelector theSelector;
   private static Object guard = new Object();
   private Hierarchy heirarchy;

   public static synchronized void init(Class mainClass)
   {
      if( theSelector == null )
      {
         String name = mainClass.getName();
         Hierarchy heirarchy = new Hierarchy(new RootCategory(Level.DEBUG));
         // Locate the log4j.xml or log4j.properties config
         InputStream is = findConfig(name, heirarchy);
         if( is == null )
            throw new IllegalStateException("Failed to find any log4j.xml config");

         DOMConfigurator config = new DOMConfigurator();
         config.doConfigure(is, heirarchy);
         theSelector = new ChapterExRepository(heirarchy);
         // Establish the RepositorySelector
         LogManager.setRepositorySelector(theSelector, guard);
      }
   }

   private ChapterExRepository(Hierarchy heirarchy)
   {
      this.heirarchy = heirarchy;
   }

   public LoggerRepository getLoggerRepository()
   {
      return heirarchy;
   }

   private static InputStream findConfig(String name, Hierarchy heirarchy)
   {
      ClassLoader tcl = Thread.currentThread().getContextClassLoader();
      InputStream is = null;

      // First look for a resource: "name / log4j-suffix(name).xml"
      String prefix = "";
      String suffix = name;
      int dot = name.lastIndexOf('.');
      if( dot >= 0 )
      {
         prefix = name.substring(0, dot);
         suffix = name.substring(dot+1);
      }
      prefix = prefix.replace('.', '/');

      String log4jxml = prefix + "/log4j-" + suffix + ".xml";
      URL resURL = tcl.getResource(log4jxml);
      if( resURL != null )
      {
         try
         {
            is = resURL.openStream();
            System.out.println("Found resURL: "+resURL);
            return is;
         }
         catch(IOException e)
         {
         }
      }

      // Next look for resource name / + log4j.xml
      log4jxml = prefix + "/log4j.xml";
      resURL = tcl.getResource(log4jxml);
      if( resURL != null )
      {
         try
         {
            is = resURL.openStream();
         }
         catch(IOException e)
         {
         }
         //System.out.println("Found resURL: "+resURL);
         return is;
      }

      // Next look for just the log4j.xml res
      log4jxml = "log4j.xml";
      resURL = tcl.getResource(log4jxml);
      if( resURL != null )
      {
         try
         {
            is = resURL.openStream();
            //System.out.println("Found resURL: "+resURL);
         }
         catch(IOException e)
         {
         }
      }
      return is;
   }
}

SendRecvClient.java

package jms;

import java.util.Properties;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
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.TextMessage;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import EDU.oswego.cs.dl.util.concurrent.CountDown;
import org.apache.log4j.Logger;
import jms.ChapterExRepository;

/**
 * A complete JMS client example program that sends a
 * TextMessage to a Queue and asynchronously receives the
 * message from the same Queue.
 *
 * @author  Scott.Stark@jboss.org
 * @version $Revision: 1.2 $
 */
public class SendRecvClient
{
    static Logger log;
    static CountDown done = new CountDown(1);
   
    QueueConnection conn;
    QueueSession session;
    Queue que;
   
    public static class ExListener
        implements MessageListener
    {
        public void onMessage(Message msg)
        {
            done.release();
            TextMessage tm = (TextMessage) msg;
            try {
                log.info("onMessage, recv text=" + tm.getText());
            } catch(Throwable t) {
                t.printStackTrace();
            }
        }
    }
   
    public void setupPTP()
        throws JMSException,
               NamingException
    {
        Properties props = new Properties();
        props.setProperty( "java.naming.factory.initial",
        "org.jnp.interfaces.NamingContextFactory" );
        props.setProperty( "java.naming.provider.url", "127.0.0.1:1099" );
        props.setProperty( "java.naming.factory.url.pkgs", "org.jboss.naming" );
        Context ctx = new InitialContext( props );
       
        //InitialContext iniCtx = new InitialContext();
        Object tmp = ctx.lookup("ConnectionFactory");
        QueueConnectionFactory qcf = (QueueConnectionFactory) tmp;
        conn = qcf.createQueueConnection();
        que = (Queue) ctx.lookup("queue/testQueue");
        session = conn.createQueueSession(false,
                                          QueueSession.AUTO_ACKNOWLEDGE);
        conn.start();
    }
   
    public void sendRecvAsync(String text)
        throws JMSException,
               NamingException
    {
        log.info("Begin sendRecvAsync");
        // Setup the PTP connection, session
        setupPTP();

        // Set the async listener
        QueueReceiver recv = session.createReceiver(que);
        recv.setMessageListener(new ExListener());

        // Send a text msg
        QueueSender send = session.createSender(que);
        TextMessage tm = session.createTextMessage(text);
        send.send(tm);
        log.info("sendRecvAsync, sent text=" + tm.getText());
        send.close();
        log.info("End sendRecvAsync");
    }
   
    public void stop()
        throws JMSException
    {
        conn.stop();
        session.close();
       // conn.close();
    }
   
    public static void main(String args[])
        throws Exception
    {
        ChapterExRepository.init(SendRecvClient.class);
        log = Logger.getLogger("SendRecvClient");
       
        log.info("Begin SendRecvClient, now=" + System.currentTimeMillis());
        SendRecvClient client = new SendRecvClient();
        client.sendRecvAsync("A text msg");
        client.done.acquire();
        client.stop();
        log.info("End SendRecvClient");
        System.exit(0);
    }
}



Log4j.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

   <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
      <param name="Target" value="System.out"/>
      <param name="Threshold" value="DEBUG"/>

      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="[%p,%c{1}] %m%n"/>
      </layout>
   </appender>

   <appender name="FILE" class="org.apache.log4j.FileAppender">
      <param name="File" value="logs/${chapter.ex}.log" />
      <param name="Append" value="false" />

      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="[%p,%c{1}] %m%n"/>
      </layout>
   </appender>

   <root>
      <level value ="DEBUG"/>
      <appender-ref ref="CONSOLE" />
      <appender-ref ref="FILE" />
   </root>

No comments:

Post a Comment