7e9a31a4f44688e052c38b3245a50b66c0fcd3f8
[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 java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.io.ObjectInputStream;
26 import java.nio.ByteBuffer;
27 import java.util.List;
28 import java.util.concurrent.BlockingQueue;
29 import java.util.concurrent.LinkedBlockingDeque;
30 import java.util.concurrent.TimeUnit;
31
32 import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder;
33 import org.onap.policy.apex.core.infrastructure.messaging.MessageListener;
34 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlock;
35 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlockHandler;
36 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.RawMessageBlock;
37 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
38 import org.slf4j.ext.XLogger;
39 import org.slf4j.ext.XLoggerFactory;
40
41 import com.google.common.eventbus.Subscribe;
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
92         try (final ByteArrayInputStream stream = new ByteArrayInputStream(dataByteBuffer.array());
93                 final ObjectInputStream ois = new ObjectInputStream(stream);) {
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             if (messageHolder != null) {
103                 final List<MESSAGE> messages = messageHolder.getMessages();
104                 if (messages != null) {
105                     messageBlockQueue.add(new MessageBlock<MESSAGE>(messages, incomingData.getConn()));
106                 }
107             }
108         } catch (final IOException | ClassNotFoundException e) {
109             LOGGER.error("Failed to process message received");
110             LOGGER.catching(e);
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      * This thread monitors the message queue and processes messages as they appear on the queue.
134      *
135      * @see java.lang.Runnable#run()
136      */
137     @Override
138     public void run() {
139         LOGGER.debug("raw message listening started");
140         thisThread = Thread.currentThread();
141
142         // Run until termination
143         while (thisThread.isAlive() && !thisThread.isInterrupted()) {
144             try {
145                 // Read message block messages from the queue and pass it to the data handler
146                 MessageBlock<MESSAGE> messageBlock = null;
147                 while ((messageBlock = messageBlockQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
148                     dataHandler.post(messageBlock);
149                 }
150             } catch (final InterruptedException e) {
151                 // restore the interrupt status
152                 Thread.currentThread().interrupt();
153                 LOGGER.debug("raw message listening has been interrupted");
154                 break;
155             }
156
157             try {
158                 // Read string messages from the queue and pass it to the data handler
159                 String stringMessage = null;
160                 while ((stringMessage = stringMessageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
161                     dataHandler.post(stringMessage);
162                 }
163             } catch (final InterruptedException e) {
164                 // restore the interrupt status
165                 Thread.currentThread().interrupt();
166                 LOGGER.debug("raw message listening has been interrupted");
167                 break;
168             }
169
170             // Wait for new messages
171             try {
172                 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 has been 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      * This method is called when a message is received on a web socket and is to be forwarded to a
203      * listener.
204      *
205      * @param data the message data containing a message
206      */
207     @Override
208     public void onMessage(final MessageBlock<MESSAGE> data) {
209         throw new UnsupportedOperationException("this operation is not supported");
210     }
211
212     /**
213      * Register a data forwarder to which messages coming in on the web socket will be forwarded.
214      *
215      * @param listener The listener to register
216      */
217     @Override
218     public void registerDataForwarder(final MessageListener<MESSAGE> listener) {
219         stateCheck(listener);
220         dataHandler.registerMessageHandler(listener);
221     }
222
223     /**
224      * Unregister a data forwarder that was previously registered on the web socket listener.
225      *
226      * @param listener The listener to unregister
227      */
228     @Override
229     public void unRegisterDataForwarder(final MessageListener<MESSAGE> listener) {
230         stateCheck(listener);
231         dataHandler.unRegisterMessageHandler(listener);
232     }
233
234     /**
235      * Sanity check for the listener and data handler.
236      *
237      * @param listener the listener to check
238      */
239     private void stateCheck(final MessageListener<MESSAGE> listener) {
240         if (listener == null) {
241             throw new IllegalArgumentException("The listener object cannot be null");
242         }
243     }
244 }