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 * Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
20 * SPDX-License-Identifier: Apache-2.0
21 * ============LICENSE_END=========================================================
24 package org.onap.policy.apex.core.infrastructure.messaging.impl.ws;
26 import com.google.common.eventbus.Subscribe;
27 import java.io.ByteArrayInputStream;
28 import java.io.IOException;
29 import java.io.ObjectInputStream;
30 import java.nio.ByteBuffer;
31 import java.util.List;
32 import java.util.concurrent.BlockingQueue;
33 import java.util.concurrent.LinkedBlockingDeque;
34 import java.util.concurrent.TimeUnit;
35 import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder;
36 import org.onap.policy.apex.core.infrastructure.messaging.MessageListener;
37 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlock;
38 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlockHandler;
39 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.RawMessageBlock;
40 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
41 import org.slf4j.ext.XLogger;
42 import org.slf4j.ext.XLoggerFactory;
45 * The Class RawMessageHandler handles raw messages being received on a Java web socket and forwards the messages to the
46 * DataHandler instance that has subscribed to the RawMessageHandler instance.
48 * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
49 * @param <M> the generic type of message being received
51 public class RawMessageHandler<M> implements WebSocketMessageListener<M>, Runnable {
52 // The logger for this class
53 private static final XLogger LOGGER = XLoggerFactory.getXLogger(RawMessageHandler.class);
55 // Repeated string constants
56 private static final String RAW_MESSAGE_LISTENING_INTERRUPTED = "raw message listening has been interrupted";
58 // The amount of time to sleep during shutdown for the thread of this message handler to stop
59 private static final int SHUTDOWN_WAIT_TIME = 10;
61 // The timeout to wait between queue poll timeouts in milliseconds
62 private static final long QUEUE_POLL_TIMEOUT = 50;
64 // A queue that temporarily holds message blocks
65 private final BlockingQueue<MessageBlock<M>> messageBlockQueue = new LinkedBlockingDeque<>();
67 // A queue that temporarily holds message blocks
68 private final BlockingQueue<String> stringMessageQueue = new LinkedBlockingDeque<>();
70 // Client applications that have subscribed for messages
71 private final MessageBlockHandler<M> dataHandler = new MessageBlockHandler<>("data-processor");
73 // The thread that the raw message handler is receiving messages on
74 private Thread thisThread = null;
77 * This method is called by the class with which this message listener has been registered.
79 * @param incomingData the data forwarded by the message reception class
83 public void onMessage(final RawMessageBlock incomingData) {
84 // Sanity check and get incoming data
85 ByteBuffer dataByteBuffer = null;
86 if (incomingData != null && incomingData.getMessage() != null) {
87 dataByteBuffer = incomingData.getMessage();
92 // Read the messages from the web socket and place them on the message queue for handling by
96 try (final var stream = new ByteArrayInputStream(dataByteBuffer.array());
97 final var ois = new ObjectInputStream(stream)) {
98 @SuppressWarnings("unchecked")
99 final MessageHolder<M> messageHolder = (MessageHolder<M>) ois.readObject();
101 if (LOGGER.isDebugEnabled()) {
102 LOGGER.debug("message {} recieved from the client {} ", messageHolder,
103 messageHolder == null ? "Apex Engine " : messageHolder.getSenderHostAddress());
106 if (messageHolder != null) {
107 final List<M> messages = messageHolder.getMessages();
108 if (messages != null) {
109 messageBlockQueue.add(new MessageBlock<>(messages, incomingData.getWebSocket()));
112 } catch (final IOException | ClassNotFoundException e) {
113 LOGGER.error("Failed to process message received");
119 * This method is called when a string message is received on a web socket and is to be forwarded to a listener.
121 * @param messageString the message string
125 public void onMessage(final String messageString) {
126 if (messageString == null) {
129 if (LOGGER.isDebugEnabled()) {
130 LOGGER.debug("message {} recieved from the client {} ", messageString);
132 stringMessageQueue.add(messageString);
136 * This method is called when a message is received on a web socket and is to be forwarded to a listener.
138 * @param data the message data containing a message
141 public void onMessage(final MessageBlock<M> data) {
142 throw new UnsupportedOperationException("this operation is not supported");
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<M> messageBlock = null;
160 while ((messageBlock = messageBlockQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
161 dataHandler.post(messageBlock);
164 // Read string messages from the queue and pass it to the data handler
165 String stringMessage = null;
166 while ((stringMessage = stringMessageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
167 dataHandler.post(stringMessage);
170 // Wait for new messages
171 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_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 * Register a data forwarder to which messages coming in on the web socket will be forwarded.
204 * @param listener The listener to register
207 public void registerDataForwarder(final MessageListener<M> listener) {
208 stateCheck(listener);
209 dataHandler.registerMessageHandler(listener);
213 * Unregister a data forwarder that was previously registered on the web socket listener.
215 * @param listener The listener to unregister
218 public void unRegisterDataForwarder(final MessageListener<M> listener) {
219 stateCheck(listener);
220 dataHandler.unRegisterMessageHandler(listener);
224 * Sanity check for the listener and data handler.
226 * @param listener the listener to check
228 private void stateCheck(final MessageListener<M> listener) {
229 if (listener == null) {
230 throw new IllegalArgumentException("The listener object cannot be null");