aboutsummaryrefslogtreecommitdiffstats
path: root/plugins/plugins-event/plugins-event-carrier/plugins-event-carrier-jms/src/main/java/org/onap/policy/apex/plugins/event/carrier/jms/ApexJmsProducer.java
blob: 44ed810fdf42d84cff2df02a83bfb70d863f9813 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
 *  Modifications Copyright (C) 2019-2021 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.apex.plugins.event.carrier.jms;

import java.io.Serializable;
import java.util.EnumMap;
import java.util.Map;
import java.util.Properties;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.Topic;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.onap.policy.apex.service.engine.event.ApexEventException;
import org.onap.policy.apex.service.engine.event.ApexEventProducer;
import org.onap.policy.apex.service.engine.event.ApexEventRuntimeException;
import org.onap.policy.apex.service.engine.event.PeeredReference;
import org.onap.policy.apex.service.engine.event.SynchronousEventCache;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerParameters;
import org.onap.policy.apex.service.parameters.eventhandler.EventHandlerPeeredMode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Concrete implementation of an Apex event producer that sends events using JMS.
 *
 * @author Liam Fallon (liam.fallon@ericsson.com)
 */
public class ApexJmsProducer implements ApexEventProducer {
    // Get a reference to the logger
    private static final Logger LOGGER = LoggerFactory.getLogger(ApexJmsProducer.class);

    // Recurring string constants
    private static final String COULD_NOT_SEND_PREFIX = "could not send event \"";
    private static final String FOR_PRODUCER_TAG = "\" for producer (";
    private static final String JMS_MESSAGE_PRODUCER_TAG = "\" on JMS message producer ";

    // The JMS parameters read from the parameter service
    private JmsCarrierTechnologyParameters jmsProducerProperties;

    // The connection to the JMS server
    private Connection connection;

    // The JMS session on which we will send events
    private Session jmsSession;

    // The producer on which we will send events
    private MessageProducer messageProducer;

    // The name for this producer
    private String name = null;

    // The peer references for this event handler
    private final Map<EventHandlerPeeredMode, PeeredReference> peerReferenceMap =
        new EnumMap<>(EventHandlerPeeredMode.class);

    /**
     * {@inheritDoc}.
     */
    @Override
    public void init(final String producerName, final EventHandlerParameters producerParameters)
                    throws ApexEventException {
        this.name = producerName;

        // Check and get the JMS Properties
        if (!(producerParameters.getCarrierTechnologyParameters() instanceof JmsCarrierTechnologyParameters)) {
            final String errorMessage = "specified producer properties are not applicable to a JMS producer ("
                            + this.name + ")";
            throw new ApexEventException(errorMessage);
        }
        jmsProducerProperties = (JmsCarrierTechnologyParameters) producerParameters.getCarrierTechnologyParameters();

        // Look up the JMS connection factory
        InitialContext jmsContext;
        ConnectionFactory connectionFactory;
        try {
            jmsContext = getInitialContext();
            connectionFactory = (ConnectionFactory) jmsContext.lookup(jmsProducerProperties.getConnectionFactory());

            // Check if we actually got a connection factory
            if (connectionFactory == null) {
                throw new IllegalArgumentException(
                                "JMS context lookup of \"" + jmsProducerProperties.getConnectionFactory()
                                                + "\" returned null for producer (" + this.name + ")");
            }
        } catch (final Exception e) {
            final String errorMessage = "lookup of JMS connection factory  \""
                            + jmsProducerProperties.getConnectionFactory() + "\" failed for JMS producer properties \""
                            + jmsProducerProperties.getJmsConsumerProperties() + FOR_PRODUCER_TAG + this.name + ")";
            throw new ApexEventException(errorMessage, e);
        }

        // Lookup the topic on which we will send events
        Topic jmsOutgoingTopic;
        try {
            jmsOutgoingTopic = (Topic) jmsContext.lookup(jmsProducerProperties.getProducerTopic());

            // Check if we actually got a topic
            if (jmsOutgoingTopic == null) {
                throw new IllegalArgumentException("JMS context lookup of \"" + jmsProducerProperties.getProducerTopic()
                                + "\" returned null for producer (" + this.name + ")");
            }
        } catch (final Exception e) {
            final String errorMessage = "lookup of JMS topic  \"" + jmsProducerProperties.getProducerTopic()
                            + "\" failed for JMS producer properties \""
                            + jmsProducerProperties.getJmsProducerProperties() + FOR_PRODUCER_TAG + this.name + ")";
            throw new ApexEventException(errorMessage, e);
        }

        // Create and start a connection to the JMS server
        try {
            connection = connectionFactory.createConnection(jmsProducerProperties.getSecurityPrincipal(),
                            jmsProducerProperties.getSecurityCredentials());
            connection.start();
        } catch (final Exception e) {
            final String errorMessage = "connection to JMS server failed for JMS properties \""
                            + jmsProducerProperties.getJmsConsumerProperties() + FOR_PRODUCER_TAG + this.name + ")";
            throw new ApexEventException(errorMessage, e);
        }

        // Create a JMS session for sending events
        try {
            jmsSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        } catch (final Exception e) {
            final String errorMessage = "creation of session to JMS server failed for JMS properties \""
                            + jmsProducerProperties.getJmsConsumerProperties() + FOR_PRODUCER_TAG + this.name + ")";
            throw new ApexEventException(errorMessage, e);
        }

        // Create a JMS message producer for sending events
        try {
            messageProducer = jmsSession.createProducer(jmsOutgoingTopic);
        } catch (final Exception e) {
            final String errorMessage = "creation of producer for sending events "
                            + "to JMS server failed for JMS properties \""
                            + jmsProducerProperties.getJmsConsumerProperties() + "\"";
            throw new ApexEventException(errorMessage, e);
        }
    }

    /**
     * Construct InitialContext. This function should not be run directly.
     * Package-private access is set for testing purposes only.
     *
     * @return InitialContext
     * @throws NamingException if a naming exception is encountered
     */
    public InitialContext getInitialContext() throws NamingException {
        return new InitialContext(jmsProducerProperties.getJmsProducerProperties());
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public String getName() {
        return name;
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public PeeredReference getPeeredReference(final EventHandlerPeeredMode peeredMode) {
        return peerReferenceMap.get(peeredMode);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void setPeeredReference(final EventHandlerPeeredMode peeredMode, final PeeredReference peeredReference) {
        peerReferenceMap.put(peeredMode, peeredReference);
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void sendEvent(final long executionId, final Properties executionProperties, final String eventname,
                    final Object eventObject) {
        // Check if this is a synchronized event, if so we have received a reply
        final SynchronousEventCache synchronousEventCache = (SynchronousEventCache) peerReferenceMap
                        .get(EventHandlerPeeredMode.SYNCHRONOUS);
        if (synchronousEventCache != null) {
            synchronousEventCache.removeCachedEventToApexIfExists(executionId);
        }

        // Check if the object to be sent is serializable
        if (!Serializable.class.isAssignableFrom(eventObject.getClass())) {
            final String errorMessage = COULD_NOT_SEND_PREFIX + eventname + JMS_MESSAGE_PRODUCER_TAG + this.name
                            + ", object of type \"" + eventObject.getClass().getName() + "\" is not serializable";
            LOGGER.warn(errorMessage);
            throw new ApexEventRuntimeException(errorMessage);
        }

        // The JMS message to send is constructed using the JMS session
        Message jmsMessage;

        // Check the type of JMS message to send
        if (jmsProducerProperties.isObjectMessageSending()) {
            // We should send a JMS Object Message
            try {
                jmsMessage = jmsSession.createObjectMessage((Serializable) eventObject);
            } catch (final Exception e) {
                final String errorMessage = COULD_NOT_SEND_PREFIX + eventname + JMS_MESSAGE_PRODUCER_TAG + this.name
                                + ", could not create JMS Object Message for object \"" + eventObject;
                LOGGER.warn(errorMessage, e);
                throw new ApexEventRuntimeException(errorMessage);
            }
        } else {
            // We should send a JMS Text Message
            try {
                jmsMessage = jmsSession.createTextMessage(eventObject.toString());
            } catch (final Exception e) {
                final String errorMessage = COULD_NOT_SEND_PREFIX + eventname + JMS_MESSAGE_PRODUCER_TAG + this.name
                                + ", could not create JMS Text Message for object \"" + eventObject;
                LOGGER.warn(errorMessage, e);
                throw new ApexEventRuntimeException(errorMessage);
            }
        }

        try {
            messageProducer.send(jmsMessage);
        } catch (final Exception e) {
            final String errorMessage = COULD_NOT_SEND_PREFIX + eventname + JMS_MESSAGE_PRODUCER_TAG + this.name
                            + ", send failed for object \"" + eventObject;
            LOGGER.warn(errorMessage, e);
            throw new ApexEventRuntimeException(errorMessage);
        }
    }

    /**
     * {@inheritDoc}.
     */
    @Override
    public void stop() {
        // Close the message producer
        try {
            messageProducer.close();
        } catch (final Exception e) {
            final String errorMessage = "failed to close JMS message producer " + this.name + " for sending messages";
            LOGGER.warn(errorMessage, e);
        }

        // Close the session
        try {
            jmsSession.close();
        } catch (final Exception e) {
            final String errorMessage = "failed to close the JMS session for  " + this.name + " for sending messages";
            LOGGER.warn(errorMessage, e);
        }

        // Close the connection to the JMS server
        try {
            connection.close();
        } catch (final Exception e) {
            final String errorMessage = "close of connection to the JMS server for  " + this.name + " failed";
            LOGGER.warn(errorMessage, e);
        }
    }
}