534bee8afcac4e6bfc2e283763f5b9a9f7a6d56f
[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 <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 the queue
89         // processing thread
90         ObjectInputStream ois = null;
91         try {
92             ois = new ObjectInputStream(new ByteArrayInputStream(dataByteBuffer.array()));
93             @SuppressWarnings("unchecked")
94             final MessageHolder<MESSAGE> messageHolder = (MessageHolder<MESSAGE>) ois.readObject();
95
96             if (LOGGER.isDebugEnabled()) {
97                 LOGGER.debug("message {} recieved from the client {} ", messageHolder.toString(),
98                         messageHolder == null ? "Apex Engine " : messageHolder.getSenderHostAddress());
99             }
100
101             final List<MESSAGE> messages = messageHolder.getMessages();
102             if (messages != null) {
103                 messageBlockQueue.add(new MessageBlock<MESSAGE>(messages, incomingData.getConn()));
104             }
105         } catch (IOException | ClassNotFoundException e) {
106             LOGGER.error("Failed to process message received");
107             LOGGER.catching(e);
108         } finally {
109             closeObjectStream(ois);
110         }
111     }
112
113     /**
114      * This method is called when a string message is received on a web socket and is to be forwarded to a listener.
115      *
116      * @param messageString the message string
117      */
118     @Override
119     @Subscribe
120     public void onMessage(final String messageString) {
121         if (messageString == null) {
122             return;
123         }
124         if (LOGGER.isDebugEnabled()) {
125             LOGGER.debug("message {} recieved from the client {} ", messageString);
126         }
127         stringMessageQueue.add(messageString);
128     }
129
130     /**
131      * Close the {@link ObjectInputStream} stream.
132      *
133      * @param ois is an instance of {@link ObjectInputStream}
134      */
135     private void closeObjectStream(final ObjectInputStream ois) {
136         if (ois != null) {
137             try {
138                 ois.close();
139             } catch (final IOException e) {
140                 LOGGER.catching(e);
141             }
142         }
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<MESSAGE> messageBlock = null;
160                 while ((messageBlock = messageBlockQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
161                     dataHandler.post(messageBlock);
162                 }
163             } catch (final InterruptedException e) {
164                 LOGGER.debug("raw message listening has been interrupted");
165                 break;
166             }
167
168             try {
169                 // Read string messages from the queue and pass it to the data handler
170                 String stringMessage = null;
171                 while ((stringMessage = stringMessageQueue.poll(1, TimeUnit.MILLISECONDS)) != null) {
172                     dataHandler.post(stringMessage);
173                 }
174             } catch (final InterruptedException e) {
175                 LOGGER.debug("raw message listening has been interrupted");
176                 break;
177             }
178
179             // Wait for new messages
180             try {
181                 Thread.sleep(QUEUE_POLL_TIMEOUT);
182             } catch (final InterruptedException e) {
183                 LOGGER.debug("raw message listening has been interrupted");
184                 break;
185             }
186         }
187
188         LOGGER.debug("raw message listening stopped");
189     }
190
191     /**
192      * Shutdown the message handler.
193      */
194     public void shutdown() {
195         LOGGER.entry("shutting down raw message listening . . .");
196
197         // Interrupt the message handling thread
198         thisThread.interrupt();
199
200         // Wait for thread shutdown
201         while (thisThread.isAlive()) {
202             ThreadUtilities.sleep(SHUTDOWN_WAIT_TIME);
203         }
204
205         LOGGER.exit("shut down raw message listening");
206     }
207
208     /**
209      * This method is called when a message is received on a web socket and is to be forwarded to a listener.
210      *
211      * @param data the message data containing a message
212      */
213     @Override
214     public void onMessage(final MessageBlock<MESSAGE> data) {
215         throw new UnsupportedOperationException("this operation is not supported");
216     }
217
218     /**
219      * Register a data forwarder to which messages coming in on the web socket will be forwarded.
220      *
221      * @param listener The listener to register
222      */
223     @Override
224     public void registerDataForwarder(final MessageListener<MESSAGE> listener) {
225         stateCheck(listener);
226         dataHandler.registerMessageHandler(listener);
227     }
228
229     /**
230      * Unregister a data forwarder that was previously registered on the web socket listener.
231      *
232      * @param listener The listener to unregister
233      */
234     @Override
235     public void unRegisterDataForwarder(final MessageListener<MESSAGE> listener) {
236         stateCheck(listener);
237         dataHandler.unRegisterMessageHandler(listener);
238     }
239
240     /**
241      * Sanity check for the listener and data handler.
242      *
243      * @param listener the listener to check
244      */
245     private void stateCheck(final MessageListener<MESSAGE> listener) {
246         if (listener == null) {
247             throw new IllegalArgumentException("The listener object cannot be null");
248         }
249         if (dataHandler == null) {
250             throw new IllegalStateException("Data handler not initialized");
251         }
252     }
253 }