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 final AtomicReference<State> state = new AtomicReference<>(State.INITIALIZED);
44 private final JmsManager jmsManager;
45 private MessageConsumer messageConsumer;
46
47 public JmsServer(final String connectionFactoryBindingName,
48 final String destinationBindingName,
49 final String username,
50 final String password) {
51 final String managerName = JmsServer.class.getName() + '@' + JmsServer.class.hashCode();
52 final JndiManager jndiManager = JndiManager.getDefaultManager(managerName);
53 jmsManager = JmsManager.getJmsManager(managerName, jndiManager, connectionFactoryBindingName,
54 destinationBindingName, username, password);
55 }
56
57 @Override
58 public State getState() {
59 return state.get();
60 }
61
62 @Override
63 public void onMessage(final Message message) {
64 try {
65 if (message instanceof ObjectMessage) {
66 final Object body = ((ObjectMessage) message).getObject();
67 if (body instanceof LogEvent) {
68 log((LogEvent) body);
69 } else {
70 LOGGER.warn("Expected ObjectMessage to contain LogEvent. Got type {} instead.", body.getClass());
71 }
72 } else {
73 LOGGER.warn("Received message of type {} and JMSType {} which cannot be handled.", message.getClass(),
74 message.getJMSType());
75 }
76 } catch (final JMSException e) {
77 LOGGER.catching(e);
78 }
79 }
80
81 @Override
82 public void initialize() {
83 }
84
85 @Override
86 public void start() {
87 if (state.compareAndSet(State.INITIALIZED, State.STARTING)) {
88 try {
89 messageConsumer = jmsManager.createMessageConsumer();
90 messageConsumer.setMessageListener(this);
91 } catch (final JMSException e) {
92 throw new LoggingException(e);
93 }
94 }
95 }
96
97 @Override
98 public void stop() {
99 try {
100 messageConsumer.close();
101 } catch (final JMSException ignored) {
102 }
103 jmsManager.release();
104 }
105
106 @Override
107 public boolean isStarted() {
108 return state.get() == State.STARTED;
109 }
110
111 @Override
112 public boolean isStopped() {
113 return state.get() == State.STOPPED;
114 }
115
116 }