2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * ================================================================================
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 * SPDX-License-Identifier: Apache-2.0
18 * ============LICENSE_END=========================================================
21 package org.onap.policy.apex.core.infrastructure.messaging.impl.ws;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.ObjectInputStream;
26 import java.nio.ByteBuffer;
27 import java.util.List;
28 import java.util.concurrent.BlockingQueue;
29 import java.util.concurrent.LinkedBlockingDeque;
30 import java.util.concurrent.TimeUnit;
32 import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder;
33 import org.onap.policy.apex.core.infrastructure.messaging.MessageListener;
34 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlock;
35 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlockHandler;
36 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.RawMessageBlock;
37 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
38 import org.slf4j.ext.XLogger;
39 import org.slf4j.ext.XLoggerFactory;
41 import com.google.common.eventbus.Subscribe;
44 * The Class RawMessageHandler handles raw messages being received on a Java web socket and forwards
45 * the messages to the DataHandler instance that has subscribed to the RawMessageHandler instance.
47 * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
48 * @param <MESSAGE> the generic type of message being received
50 public class RawMessageHandler<MESSAGE> implements WebSocketMessageListener<MESSAGE>, Runnable {
51 // The logger for this class
52 private static final XLogger LOGGER = XLoggerFactory.getXLogger(RawMessageHandler.class);
54 // The amount of time to sleep during shutdown for the thread of this message handler to stop
55 private static final int SHUTDOWN_WAIT_TIME = 10;
57 // The timeout to wait between queue poll timeouts in milliseconds
58 private static final long QUEUE_POLL_TIMEOUT = 50;
60 // A queue that temporarily holds message blocks
61 private final BlockingQueue<MessageBlock<MESSAGE>> messageBlockQueue = new LinkedBlockingDeque<>();
63 // A queue that temporarily holds message blocks
64 private final BlockingQueue<String> stringMessageQueue = new LinkedBlockingDeque<>();
66 // Client applications that have subscribed for messages
67 private final MessageBlockHandler<MESSAGE> dataHandler = new MessageBlockHandler<MESSAGE>("data-processor");
69 // The thread that the raw message handler is receiving messages on
70 private Thread thisThread = null;
73 * This method is called by the class with which this message listener has been registered.
75 * @param incomingData the data forwarded by the message reception class
79 public void onMessage(final RawMessageBlock incomingData) {
80 // Sanity check and get incoming data
81 ByteBuffer dataByteBuffer = null;
82 if (incomingData != null && incomingData.getMessage() != null) {
83 dataByteBuffer = incomingData.getMessage();
88 // Read the messages from the web socket and place them on the message queue for handling by
92 try (final ByteArrayInputStream stream = new ByteArrayInputStream(dataByteBuffer.array());
93 final ObjectInputStream ois = new ObjectInputStream(stream);) {
94 @SuppressWarnings("unchecked")
95 final MessageHolder<MESSAGE> messageHolder = (MessageHolder<MESSAGE>) ois.readObject();
97 if (LOGGER.isDebugEnabled()) {
98 LOGGER.debug("message {} recieved from the client {} ", messageHolder,
99 messageHolder == null ? "Apex Engine " : messageHolder.getSenderHostAddress());
102 if (messageHolder != null) {
103 final List<MESSAGE> messages = messageHolder.getMessages();
104 if (messages != null) {
105 messageBlockQueue.add(new MessageBlock<MESSAGE>(messages, incomingData.getConn()));
108 } catch (final IOException | ClassNotFoundException e) {
109 LOGGER.error("Failed to process message received");
115 * This method is called when a string message is received on a web socket and is to be
116 * forwarded to a listener.
118 * @param messageString the message string
122 public void onMessage(final String messageString) {
123 if (messageString == null) {
126 if (LOGGER.isDebugEnabled()) {
127 LOGGER.debug("message {} recieved from the client {} ", messageString);
129 stringMessageQueue.add(messageString);
133 * This thread monitors the message queue and processes messages as they appear on the queue.
135 * @see java.lang.Runnable#run()
139 LOGGER.debug("raw message listening started");
140 thisThread = Thread.currentThread();
142 // Run until termination
143 while (thisThread.isAlive() && !thisThread.isInterrupted()) {
145 // Read message block messages from the queue and pass it to the data handler
146 MessageBlock<MESSAGE> messageBlock = null;
147 while ((messageBlock = messageBlockQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
148 dataHandler.post(messageBlock);
150 } catch (final InterruptedException e) {
151 // restore the interrupt status
152 Thread.currentThread().interrupt();
153 LOGGER.debug("raw message listening has been interrupted");
158 // Read string messages from the queue and pass it to the data handler
159 String stringMessage = null;
160 while ((stringMessage = stringMessageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
161 dataHandler.post(stringMessage);
163 } catch (final InterruptedException e) {
164 // restore the interrupt status
165 Thread.currentThread().interrupt();
166 LOGGER.debug("raw message listening has been interrupted");
170 // Wait for new messages
172 Thread.sleep(QUEUE_POLL_TIMEOUT);
173 } catch (final InterruptedException e) {
174 // restore the interrupt status
175 Thread.currentThread().interrupt();
176 LOGGER.debug("raw message listening has been interrupted");
181 LOGGER.debug("raw message listening stopped");
185 * Shutdown the message handler.
187 public void shutdown() {
188 LOGGER.entry("shutting down raw message listening . . .");
190 // Interrupt the message handling thread
191 thisThread.interrupt();
193 // Wait for thread shutdown
194 while (thisThread.isAlive()) {
195 ThreadUtilities.sleep(SHUTDOWN_WAIT_TIME);
198 LOGGER.exit("shut down raw message listening");
202 * This method is called when a message is received on a web socket and is to be forwarded to a
205 * @param data the message data containing a message
208 public void onMessage(final MessageBlock<MESSAGE> data) {
209 throw new UnsupportedOperationException("this operation is not supported");
213 * Register a data forwarder to which messages coming in on the web socket will be forwarded.
215 * @param listener The listener to register
218 public void registerDataForwarder(final MessageListener<MESSAGE> listener) {
219 stateCheck(listener);
220 dataHandler.registerMessageHandler(listener);
224 * Unregister a data forwarder that was previously registered on the web socket listener.
226 * @param listener The listener to unregister
229 public void unRegisterDataForwarder(final MessageListener<MESSAGE> listener) {
230 stateCheck(listener);
231 dataHandler.unRegisterMessageHandler(listener);
235 * Sanity check for the listener and data handler.
237 * @param listener the listener to check
239 private void stateCheck(final MessageListener<MESSAGE> listener) {
240 if (listener == null) {
241 throw new IllegalArgumentException("The listener object cannot be null");