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