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