0cdf76ffc416fdb92f5cd45ff2f7f9b2d7e81777
[policy/apex-pdp.git] /
1 /*-
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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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.
19  *
20  * SPDX-License-Identifier: Apache-2.0
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.policy.apex.core.infrastructure.messaging.impl.ws;
25
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;
43
44 /**
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.
47  *
48  * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
49  * @param <M> the generic type of message being received
50  */
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);
54
55     // Repeated string constants
56     private static final String RAW_MESSAGE_LISTENING_INTERRUPTED = "raw message listening has been interrupted";
57
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;
60
61     // The timeout to wait between queue poll timeouts in milliseconds
62     private static final long QUEUE_POLL_TIMEOUT = 50;
63
64     // A queue that temporarily holds message blocks
65     private final BlockingQueue<MessageBlock<M>> messageBlockQueue = new LinkedBlockingDeque<>();
66
67     // A queue that temporarily holds message blocks
68     private final BlockingQueue<String> stringMessageQueue = new LinkedBlockingDeque<>();
69
70     // Client applications that have subscribed for messages
71     private final MessageBlockHandler<M> dataHandler = new MessageBlockHandler<>("data-processor");
72
73     // The thread that the raw message handler is receiving messages on
74     private Thread thisThread = null;
75
76     /**
77      * This method is called by the class with which this message listener has been registered.
78      *
79      * @param incomingData the data forwarded by the message reception class
80      */
81     @Override
82     @Subscribe
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();
88         } else {
89             return;
90         }
91
92         // Read the messages from the web socket and place them on the message queue for handling by
93         // the queue
94         // processing thread
95
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();
100
101             if (LOGGER.isDebugEnabled()) {
102                 LOGGER.debug("message {} recieved from the client {} ", messageHolder,
103                                 messageHolder == null ? "Apex Engine " : messageHolder.getSenderHostAddress());
104             }
105
106             if (messageHolder != null) {
107                 final List<M> messages = messageHolder.getMessages();
108                 if (messages != null) {
109                     messageBlockQueue.add(new MessageBlock<>(messages, incomingData.getWebSocket()));
110                 }
111             }
112         } catch (final IOException | ClassNotFoundException e) {
113             LOGGER.error("Failed to process message received");
114             LOGGER.catching(e);
115         }
116     }
117
118     /**
119      * This method is called when a string message is received on a web socket and is to be forwarded to a listener.
120      *
121      * @param messageString the message string
122      */
123     @Override
124     @Subscribe
125     public void onMessage(final String messageString) {
126         if (messageString == null) {
127             return;
128         }
129         if (LOGGER.isDebugEnabled()) {
130             LOGGER.debug("message {} recieved from the client {} ", messageString);
131         }
132         stringMessageQueue.add(messageString);
133     }
134
135     /**
136      * This method is called when a message is received on a web socket and is to be forwarded to a listener.
137      *
138      * @param data the message data containing a message
139      */
140     @Override
141     public void onMessage(final MessageBlock<M> data) {
142         throw new UnsupportedOperationException("this operation is not supported");
143     }
144
145     /**
146      * This thread monitors the message queue and processes messages as they appear on the queue.
147      *
148      * @see java.lang.Runnable#run()
149      */
150     @Override
151     public void run() {
152         LOGGER.debug("raw message listening started");
153         thisThread = Thread.currentThread();
154
155         // Run until termination
156         while (thisThread.isAlive() && !thisThread.isInterrupted()) {
157             try {
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);
162                 }
163
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);
168                 }
169
170                 // Wait for new messages
171                 Thread.sleep(QUEUE_POLL_TIMEOUT);
172
173             } catch (final InterruptedException e) {
174                 // restore the interrupt status
175                 Thread.currentThread().interrupt();
176                 LOGGER.debug(RAW_MESSAGE_LISTENING_INTERRUPTED);
177                 break;
178             }
179         }
180
181         LOGGER.debug("raw message listening stopped");
182     }
183
184     /**
185      * Shutdown the message handler.
186      */
187     public void shutdown() {
188         LOGGER.entry("shutting down raw message listening . . .");
189
190         // Interrupt the message handling thread
191         thisThread.interrupt();
192
193         // Wait for thread shutdown
194         while (thisThread.isAlive()) {
195             ThreadUtilities.sleep(SHUTDOWN_WAIT_TIME);
196         }
197
198         LOGGER.exit("shut down raw message listening");
199     }
200
201     /**
202      * Register a data forwarder to which messages coming in on the web socket will be forwarded.
203      *
204      * @param listener The listener to register
205      */
206     @Override
207     public void registerDataForwarder(final MessageListener<M> listener) {
208         stateCheck(listener);
209         dataHandler.registerMessageHandler(listener);
210     }
211
212     /**
213      * Unregister a data forwarder that was previously registered on the web socket listener.
214      *
215      * @param listener The listener to unregister
216      */
217     @Override
218     public void unRegisterDataForwarder(final MessageListener<M> listener) {
219         stateCheck(listener);
220         dataHandler.unRegisterMessageHandler(listener);
221     }
222
223     /**
224      * Sanity check for the listener and data handler.
225      *
226      * @param listener the listener to check
227      */
228     private void stateCheck(final MessageListener<M> listener) {
229         if (listener == null) {
230             throw new IllegalArgumentException("The listener object cannot be null");
231         }
232     }
233 }