2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2016-2018 Ericsson. All rights reserved.
4 * Modifications Copyright (C) 2019-2020 Nordix Foundation.
5 * Modifications Copyright (C) 2021 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.apex.core.infrastructure.messaging.impl.ws;
25 import com.google.common.eventbus.Subscribe;
26 import java.io.ByteArrayInputStream;
27 import java.io.IOException;
28 import java.io.ObjectInputStream;
29 import java.nio.ByteBuffer;
30 import java.util.List;
31 import java.util.concurrent.BlockingQueue;
32 import java.util.concurrent.LinkedBlockingDeque;
33 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 <M> the generic type of message being received
50 public class RawMessageHandler<M> implements WebSocketMessageListener<M>, Runnable {
51 // The logger for this class
52 private static final XLogger LOGGER = XLoggerFactory.getXLogger(RawMessageHandler.class);
54 // Repeated string constants
55 private static final String RAW_MESSAGE_LISTENING_INTERRUPTED = "raw message listening has been interrupted";
57 // The amount of time to sleep during shutdown for the thread of this message handler to stop
58 private static final int SHUTDOWN_WAIT_TIME = 10;
60 // The timeout to wait between queue poll timeouts in milliseconds
61 private static final long QUEUE_POLL_TIMEOUT = 50;
63 // A queue that temporarily holds message blocks
64 private final BlockingQueue<MessageBlock<M>> messageBlockQueue = new LinkedBlockingDeque<>();
66 // A queue that temporarily holds message blocks
67 private final BlockingQueue<String> stringMessageQueue = new LinkedBlockingDeque<>();
69 // Client applications that have subscribed for messages
70 private final MessageBlockHandler<M> dataHandler = new MessageBlockHandler<>("data-processor");
72 // The thread that the raw message handler is receiving messages on
73 private Thread thisThread = null;
76 * This method is called by the class with which this message listener has been registered.
78 * @param incomingData the data forwarded by the message reception class
82 public void onMessage(final RawMessageBlock incomingData) {
83 // Sanity check and get incoming data
84 ByteBuffer dataByteBuffer = null;
85 if (incomingData != null && incomingData.getMessage() != null) {
86 dataByteBuffer = incomingData.getMessage();
91 // Read the messages from the web socket and place them on the message queue for handling by
95 try (final ByteArrayInputStream stream = new ByteArrayInputStream(dataByteBuffer.array());
96 final ObjectInputStream ois = new ObjectInputStream(stream)) {
97 @SuppressWarnings("unchecked")
98 final MessageHolder<M> messageHolder = (MessageHolder<M>) ois.readObject();
100 if (LOGGER.isDebugEnabled()) {
101 LOGGER.debug("message {} recieved from the client {} ", messageHolder,
102 messageHolder == null ? "Apex Engine " : messageHolder.getSenderHostAddress());
105 if (messageHolder != null) {
106 final List<M> messages = messageHolder.getMessages();
107 if (messages != null) {
108 messageBlockQueue.add(new MessageBlock<>(messages, incomingData.getConn()));
111 } catch (final IOException | ClassNotFoundException e) {
112 LOGGER.error("Failed to process message received");
118 * This method is called when a string message is received on a web socket and is to be forwarded to a listener.
120 * @param messageString the message string
124 public void onMessage(final String messageString) {
125 if (messageString == null) {
128 if (LOGGER.isDebugEnabled()) {
129 LOGGER.debug("message {} recieved from the client {} ", messageString);
131 stringMessageQueue.add(messageString);
135 * This method is called when a message is received on a web socket and is to be forwarded to a listener.
137 * @param data the message data containing a message
140 public void onMessage(final MessageBlock<M> data) {
141 throw new UnsupportedOperationException("this operation is not supported");
145 * This thread monitors the message queue and processes messages as they appear on the queue.
147 * @see java.lang.Runnable#run()
151 LOGGER.debug("raw message listening started");
152 thisThread = Thread.currentThread();
154 // Run until termination
155 while (thisThread.isAlive() && !thisThread.isInterrupted()) {
157 // Read message block messages from the queue and pass it to the data handler
158 MessageBlock<M> messageBlock = null;
159 while ((messageBlock = messageBlockQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
160 dataHandler.post(messageBlock);
163 // Read string messages from the queue and pass it to the data handler
164 String stringMessage = null;
165 while ((stringMessage = stringMessageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
166 dataHandler.post(stringMessage);
169 // Wait for new messages
170 Thread.sleep(QUEUE_POLL_TIMEOUT);
172 } catch (final InterruptedException e) {
173 // restore the interrupt status
174 Thread.currentThread().interrupt();
175 LOGGER.debug(RAW_MESSAGE_LISTENING_INTERRUPTED);
180 LOGGER.debug("raw message listening stopped");
184 * Shutdown the message handler.
186 public void shutdown() {
187 LOGGER.entry("shutting down raw message listening . . .");
189 // Interrupt the message handling thread
190 thisThread.interrupt();
192 // Wait for thread shutdown
193 while (thisThread.isAlive()) {
194 ThreadUtilities.sleep(SHUTDOWN_WAIT_TIME);
197 LOGGER.exit("shut down raw message listening");
201 * Register a data forwarder to which messages coming in on the web socket will be forwarded.
203 * @param listener The listener to register
206 public void registerDataForwarder(final MessageListener<M> listener) {
207 stateCheck(listener);
208 dataHandler.registerMessageHandler(listener);
212 * Unregister a data forwarder that was previously registered on the web socket listener.
214 * @param listener The listener to unregister
217 public void unRegisterDataForwarder(final MessageListener<M> listener) {
218 stateCheck(listener);
219 dataHandler.unRegisterMessageHandler(listener);
223 * Sanity check for the listener and data handler.
225 * @param listener the listener to check
227 private void stateCheck(final MessageListener<M> listener) {
228 if (listener == null) {
229 throw new IllegalArgumentException("The listener object cannot be null");