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 the messages to the
45 * 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 the queue
90 ObjectInputStream ois = null;
92 ois = new ObjectInputStream(new ByteArrayInputStream(dataByteBuffer.array()));
93 @SuppressWarnings("unchecked")
94 final MessageHolder<MESSAGE> messageHolder = (MessageHolder<MESSAGE>) ois.readObject();
96 if (LOGGER.isDebugEnabled()) {
97 LOGGER.debug("message {} recieved from the client {} ", messageHolder.toString(),
98 messageHolder == null ? "Apex Engine " : messageHolder.getSenderHostAddress());
101 final List<MESSAGE> messages = messageHolder.getMessages();
102 if (messages != null) {
103 messageBlockQueue.add(new MessageBlock<MESSAGE>(messages, incomingData.getConn()));
105 } catch (IOException | ClassNotFoundException e) {
106 LOGGER.error("Failed to process message received");
109 closeObjectStream(ois);
114 * This method is called when a string message is received on a web socket and is to be forwarded to a listener.
116 * @param messageString the message string
120 public void onMessage(final String messageString) {
121 if (messageString == null) {
124 if (LOGGER.isDebugEnabled()) {
125 LOGGER.debug("message {} recieved from the client {} ", messageString);
127 stringMessageQueue.add(messageString);
131 * Close the {@link ObjectInputStream} stream.
133 * @param ois is an instance of {@link ObjectInputStream}
135 private void closeObjectStream(final ObjectInputStream ois) {
139 } catch (final IOException e) {
146 * This thread monitors the message queue and processes messages as they appear on the queue.
148 * @see java.lang.Runnable#run()
152 LOGGER.debug("raw message listening started");
153 thisThread = Thread.currentThread();
155 // Run until termination
156 while (thisThread.isAlive() && !thisThread.isInterrupted()) {
158 // Read message block messages from the queue and pass it to the data handler
159 MessageBlock<MESSAGE> messageBlock = null;
160 while ((messageBlock = messageBlockQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
161 dataHandler.post(messageBlock);
163 } catch (final InterruptedException e) {
164 LOGGER.debug("raw message listening has been interrupted");
169 // Read string messages from the queue and pass it to the data handler
170 String stringMessage = null;
171 while ((stringMessage = stringMessageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
172 dataHandler.post(stringMessage);
174 } catch (final InterruptedException e) {
175 LOGGER.debug("raw message listening has been interrupted");
179 // Wait for new messages
181 Thread.sleep(QUEUE_POLL_TIMEOUT);
182 } catch (final InterruptedException e) {
183 LOGGER.debug("raw message listening has been interrupted");
188 LOGGER.debug("raw message listening stopped");
192 * Shutdown the message handler.
194 public void shutdown() {
195 LOGGER.entry("shutting down raw message listening . . .");
197 // Interrupt the message handling thread
198 thisThread.interrupt();
200 // Wait for thread shutdown
201 while (thisThread.isAlive()) {
202 ThreadUtilities.sleep(SHUTDOWN_WAIT_TIME);
205 LOGGER.exit("shut down raw message listening");
209 * This method is called when a message is received on a web socket and is to be forwarded to a listener.
211 * @param data the message data containing a message
214 public void onMessage(final MessageBlock<MESSAGE> data) {
215 throw new UnsupportedOperationException("this operation is not supported");
219 * Register a data forwarder to which messages coming in on the web socket will be forwarded.
221 * @param listener The listener to register
224 public void registerDataForwarder(final MessageListener<MESSAGE> listener) {
225 stateCheck(listener);
226 dataHandler.registerMessageHandler(listener);
230 * Unregister a data forwarder that was previously registered on the web socket listener.
232 * @param listener The listener to unregister
235 public void unRegisterDataForwarder(final MessageListener<MESSAGE> listener) {
236 stateCheck(listener);
237 dataHandler.unRegisterMessageHandler(listener);
241 * Sanity check for the listener and data handler.
243 * @param listener the listener to check
245 private void stateCheck(final MessageListener<MESSAGE> listener) {
246 if (listener == null) {
247 throw new IllegalArgumentException("The listener object cannot be null");
249 if (dataHandler == null) {
250 throw new IllegalStateException("Data handler not initialized");