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 com.google.common.eventbus.Subscribe;
25 import java.io.ByteArrayInputStream;
26 import java.io.IOException;
27 import java.io.ObjectInputStream;
28 import java.nio.ByteBuffer;
29 import java.util.List;
30 import java.util.concurrent.BlockingQueue;
31 import java.util.concurrent.LinkedBlockingDeque;
32 import java.util.concurrent.TimeUnit;
34 import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder;
35 import org.onap.policy.apex.core.infrastructure.messaging.MessageListener;
36 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlock;
37 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlockHandler;
38 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.RawMessageBlock;
39 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
40 import org.slf4j.ext.XLogger;
41 import org.slf4j.ext.XLoggerFactory;
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
91 ObjectInputStream ois = null;
93 ois = new ObjectInputStream(new ByteArrayInputStream(dataByteBuffer.array()));
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 final List<MESSAGE> messages = messageHolder.getMessages();
103 if (messages != null) {
104 messageBlockQueue.add(new MessageBlock<MESSAGE>(messages, incomingData.getConn()));
106 } catch (IOException | ClassNotFoundException e) {
107 LOGGER.error("Failed to process message received");
110 closeObjectStream(ois);
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 * Close the {@link ObjectInputStream} stream.
135 * @param ois is an instance of {@link ObjectInputStream}
137 private void closeObjectStream(final ObjectInputStream ois) {
141 } catch (final IOException e) {
148 * This thread monitors the message queue and processes messages as they appear on the queue.
150 * @see java.lang.Runnable#run()
154 LOGGER.debug("raw message listening started");
155 thisThread = Thread.currentThread();
157 // Run until termination
158 while (thisThread.isAlive() && !thisThread.isInterrupted()) {
160 // Read message block messages from the queue and pass it to the data handler
161 MessageBlock<MESSAGE> messageBlock = null;
162 while ((messageBlock = messageBlockQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
163 dataHandler.post(messageBlock);
165 } catch (final InterruptedException e) {
166 // restore the interrupt status
167 Thread.currentThread().interrupt();
168 LOGGER.debug("raw message listening has been interrupted");
173 // Read string messages from the queue and pass it to the data handler
174 String stringMessage = null;
175 while ((stringMessage = stringMessageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
176 dataHandler.post(stringMessage);
178 } catch (final InterruptedException e) {
179 // restore the interrupt status
180 Thread.currentThread().interrupt();
181 LOGGER.debug("raw message listening has been interrupted");
185 // Wait for new messages
187 Thread.sleep(QUEUE_POLL_TIMEOUT);
188 } catch (final InterruptedException e) {
189 // restore the interrupt status
190 Thread.currentThread().interrupt();
191 LOGGER.debug("raw message listening has been interrupted");
196 LOGGER.debug("raw message listening stopped");
200 * Shutdown the message handler.
202 public void shutdown() {
203 LOGGER.entry("shutting down raw message listening . . .");
205 // Interrupt the message handling thread
206 thisThread.interrupt();
208 // Wait for thread shutdown
209 while (thisThread.isAlive()) {
210 ThreadUtilities.sleep(SHUTDOWN_WAIT_TIME);
213 LOGGER.exit("shut down raw message listening");
217 * This method is called when a message is received on a web socket and is to be forwarded to a
220 * @param data the message data containing a message
223 public void onMessage(final MessageBlock<MESSAGE> data) {
224 throw new UnsupportedOperationException("this operation is not supported");
228 * Register a data forwarder to which messages coming in on the web socket will be forwarded.
230 * @param listener The listener to register
233 public void registerDataForwarder(final MessageListener<MESSAGE> listener) {
234 stateCheck(listener);
235 dataHandler.registerMessageHandler(listener);
239 * Unregister a data forwarder that was previously registered on the web socket listener.
241 * @param listener The listener to unregister
244 public void unRegisterDataForwarder(final MessageListener<MESSAGE> listener) {
245 stateCheck(listener);
246 dataHandler.unRegisterMessageHandler(listener);
250 * Sanity check for the listener and data handler.
252 * @param listener the listener to check
254 private void stateCheck(final MessageListener<MESSAGE> listener) {
255 if (listener == null) {
256 throw new IllegalArgumentException("The listener object cannot be null");