View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * 
4    * Copyright (C) 1999-2006, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  
11  package ch.qos.logback.classic.net;
12  
13  import java.io.BufferedReader;
14  import java.io.InputStreamReader;
15  import java.util.Properties;
16  
17  import javax.jms.JMSException;
18  import javax.jms.MessageConsumer;
19  import javax.jms.ObjectMessage;
20  import javax.jms.Queue;
21  import javax.jms.QueueConnection;
22  import javax.jms.QueueConnectionFactory;
23  import javax.jms.QueueSession;
24  import javax.jms.Session;
25  import javax.naming.Context;
26  import javax.naming.InitialContext;
27  import javax.naming.NameNotFoundException;
28  import javax.naming.NamingException;
29  
30  import org.slf4j.LoggerFactory;
31  
32  import ch.qos.logback.classic.Logger;
33  import ch.qos.logback.classic.LoggerContext;
34  import ch.qos.logback.classic.spi.LoggingEvent;
35  import ch.qos.logback.classic.util.ContextInitializer;
36  
37  /**
38   * A simple application that consumes logging events sent by a {@link
39   * JMSQueueAppender}.
40   * 
41   * @author Ceki Gülcü
42   */
43  public class JMSQueueSink implements javax.jms.MessageListener {
44  
45    private Logger logger = (Logger)LoggerFactory.getLogger(JMSTopicSink.class);
46  
47    static public void main(String[] args) throws Exception {
48      if (args.length < 2) {
49        usage("Wrong number of arguments.");
50      }
51  
52      String qcfBindingName = args[0];
53      String queueBindingName = args[1];
54      String username = null;
55      String password = null;
56      if (args.length == 4) {
57        username = args[2];
58        password = args[3];
59      }
60  
61      LoggerContext loggerContext = (LoggerContext) LoggerFactory
62          .getILoggerFactory();
63      new ContextInitializer(loggerContext).autoConfig();
64  
65      new JMSQueueSink(qcfBindingName, queueBindingName, username, password);
66  
67      BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
68      // Loop until the word "exit" is typed
69      System.out.println("Type \"exit\" to quit JMSQueueSink.");
70      while (true) {
71        String s = stdin.readLine();
72        if (s.equalsIgnoreCase("exit")) {
73          System.out.println("Exiting. Kill the application if it does not exit "
74              + "due to daemon threads.");
75          return;
76        }
77      }
78    }
79  
80    public JMSQueueSink(String qcfBindingName, String queueBindingName,
81        String username, String password) {
82  
83      try {
84        Properties env = new Properties();
85        env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
86        env.put(Context.PROVIDER_URL, "tcp://localhost:61616");
87        Context ctx = new InitialContext(env);
88        QueueConnectionFactory queueConnectionFactory;
89        queueConnectionFactory = (QueueConnectionFactory) lookup(ctx,
90            qcfBindingName);
91        System.out.println("Queue Cnx Factory found");
92        Queue queue = (Queue) ctx.lookup(queueBindingName);
93        System.out.println("Queue found: " + queue.getQueueName());
94  
95        QueueConnection queueConnection = queueConnectionFactory
96            .createQueueConnection(username, password);
97        System.out.println("Queue Connection created");
98        
99        QueueSession queueSession = queueConnection.createQueueSession(false,
100           Session.AUTO_ACKNOWLEDGE);
101 
102       MessageConsumer queueConsumer = queueSession.createConsumer(queue);
103 
104       queueConsumer.setMessageListener(this);
105       
106       queueConnection.start();
107       System.out.println("Queue Connection started");
108       
109     } catch (Exception e) {
110       logger.error("Could not read JMS message.", e);
111     }
112   }
113 
114   public void onMessage(javax.jms.Message message) {
115     LoggingEvent event;
116     try {
117       if (message instanceof ObjectMessage) {
118         ObjectMessage objectMessage = (ObjectMessage) message;
119         event = (LoggingEvent) objectMessage.getObject();
120         Logger log = (Logger) LoggerFactory.getLogger(event.getLoggerRemoteView().getName());
121         log.callAppenders(event);
122       } else {
123         logger.warn("Received message is of type " + message.getJMSType()
124             + ", was expecting ObjectMessage.");
125       }
126     } catch (JMSException jmse) {
127       logger.error("Exception thrown while processing incoming message.", jmse);
128     }
129   }
130 
131   protected Object lookup(Context ctx, String name)
132       throws NamingException {
133     try {
134       return ctx.lookup(name);
135     } catch (NameNotFoundException e) {
136       logger.error("Could not find name [" + name + "].");
137       throw e;
138     }
139   }
140 
141   static void usage(String msg) {
142     System.err.println(msg);
143     System.err
144         .println("Usage: java "
145             + JMSQueueSink.class.getName()
146             + " QueueConnectionFactoryBindingName QueueBindingName Username Password");
147     System.exit(1);
148   }
149 }