1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.logging.log4j.core.net.server;
19
20 import java.util.concurrent.atomic.AtomicReference;
21 import javax.jms.JMSException;
22 import javax.jms.Message;
23 import javax.jms.MessageConsumer;
24 import javax.jms.MessageListener;
25 import javax.jms.ObjectMessage;
26
27 import org.apache.logging.log4j.Logger;
28 import org.apache.logging.log4j.LoggingException;
29 import org.apache.logging.log4j.core.LifeCycle;
30 import org.apache.logging.log4j.core.LogEvent;
31 import org.apache.logging.log4j.core.LogEventListener;
32 import org.apache.logging.log4j.core.appender.mom.JmsManager;
33 import org.apache.logging.log4j.core.net.JndiManager;
34 import org.apache.logging.log4j.status.StatusLogger;
35
36
37
38
39
40
41 public class JmsServer extends LogEventListener implements MessageListener, LifeCycle {
42
43 private static final Logger LOGGER = StatusLogger.getLogger();
44 private final AtomicReference<State> state = new AtomicReference<State>(State.INITIALIZED);
45 private final JmsManager jmsManager;
46 private MessageConsumer messageConsumer;
47
48 public JmsServer(final String connectionFactoryBindingName,
49 final String destinationBindingName,
50 final String username,
51 final String password) {
52 final String managerName = JmsServer.class.getName() + '@' + JmsServer.class.hashCode();
53 final JndiManager jndiManager = JndiManager.getDefaultManager(managerName);
54 jmsManager = JmsManager.getJmsManager(managerName, jndiManager, connectionFactoryBindingName,
55 destinationBindingName, username, password);
56 }
57
58 @Override
59 public State getState() {
60 return state.get();
61 }
62
63 @Override
64 public void onMessage(final Message message) {
65 try {
66 if (message instanceof ObjectMessage) {
67 final Object body = ((ObjectMessage) message).getObject();
68 if (body instanceof LogEvent) {
69 log((LogEvent) body);
70 } else {
71 LOGGER.warn("Expected ObjectMessage to contain LogEvent. Got type {} instead.", body.getClass());
72 }
73 } else {
74 LOGGER.warn("Received message of type {} and JMSType {} which cannot be handled.", message.getClass(),
75 message.getJMSType());
76 }
77 } catch (final JMSException e) {
78 LOGGER.catching(e);
79 }
80 }
81
82 @Override
83 public void start() {
84 if (state.compareAndSet(State.INITIALIZED, State.STARTING)) {
85 try {
86 messageConsumer = jmsManager.createMessageConsumer();
87 messageConsumer.setMessageListener(this);
88 } catch (final JMSException e) {
89 throw new LoggingException(e);
90 }
91 }
92 }
93
94 @Override
95 public void stop() {
96 try {
97 messageConsumer.close();
98 } catch (final JMSException ignored) {
99 }
100 jmsManager.release();
101 }
102
103 @Override
104 public boolean isStarted() {
105 return state.get() == State.STARTED;
106 }
107
108 @Override
109 public boolean isStopped() {
110 return state.get() == State.STOPPED;
111 }
112
113 }