e0bf0ea6b43ea053826aa69678359b75a08cc873
[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 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<M>(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             } catch (final InterruptedException e) {
163                 // restore the interrupt status
164                 Thread.currentThread().interrupt();
165                 LOGGER.debug(RAW_MESSAGE_LISTENING_INTERRUPTED);
166                 break;
167             }
168
169             try {
170                 // Read string messages from the queue and pass it to the data handler
171                 String stringMessage = null;
172                 while ((stringMessage = stringMessageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
173                     dataHandler.post(stringMessage);
174                 }
175             } catch (final InterruptedException e) {
176                 // restore the interrupt status
177                 Thread.currentThread().interrupt();
178                 LOGGER.debug(RAW_MESSAGE_LISTENING_INTERRUPTED);
179                 break;
180             }
181
182             // Wait for new messages
183             try {
184                 Thread.sleep(QUEUE_POLL_TIMEOUT);
185             } catch (final InterruptedException e) {
186                 // restore the interrupt status
187                 Thread.currentThread().interrupt();
188                 LOGGER.debug(RAW_MESSAGE_LISTENING_INTERRUPTED);
189                 break;
190             }
191         }
192
193         LOGGER.debug("raw message listening stopped");
194     }
195
196     /**
197      * Shutdown the message handler.
198      */
199     public void shutdown() {
200         LOGGER.entry("shutting down raw message listening . . .");
201
202         // Interrupt the message handling thread
203         thisThread.interrupt();
204
205         // Wait for thread shutdown
206         while (thisThread.isAlive()) {
207             ThreadUtilities.sleep(SHUTDOWN_WAIT_TIME);
208         }
209
210         LOGGER.exit("shut down raw message listening");
211     }
212
213     /**
214      * Register a data forwarder to which messages coming in on the web socket will be forwarded.
215      *
216      * @param listener The listener to register
217      */
218     @Override
219     public void registerDataForwarder(final MessageListener<M> listener) {
220         stateCheck(listener);
221         dataHandler.registerMessageHandler(listener);
222     }
223
224     /**
225      * Unregister a data forwarder that was previously registered on the web socket listener.
226      *
227      * @param listener The listener to unregister
228      */
229     @Override
230     public void unRegisterDataForwarder(final MessageListener<M> listener) {
231         stateCheck(listener);
232         dataHandler.unRegisterMessageHandler(listener);
233     }
234
235     /**
236      * Sanity check for the listener and data handler.
237      *
238      * @param listener the listener to check
239      */
240     private void stateCheck(final MessageListener<M> listener) {
241         if (listener == null) {
242             throw new IllegalArgumentException("The listener object cannot be null");
243         }
244     }
245 }