View Javadoc

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