dd9aac122ada125bd3bc55f76404495117b43410
[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.client;
22
23 import java.net.URI;
24
25 import org.java_websocket.WebSocket;
26 import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder;
27 import org.onap.policy.apex.core.infrastructure.messaging.MessagingService;
28 import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils;
29 import org.onap.policy.apex.core.infrastructure.threading.ThreadUtilities;
30
31 /**
32  * The Class MessagingClient is the class that wraps web socket handling, message sending, and
33  * message reception on the client side of a web socket in Apex.
34  *
35  * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
36  * @param <M> the generic type
37  */
38 public class MessagingClient<M> extends InternalMessageBusClient<M> implements MessagingService<M> {
39     // The length of time to wait for a connection to a web socket server before aborting
40     private static final int CONNECTION_TIMEOUT_TIME_MS = 3000;
41
42     // The length of time to wait before checking if a connection to a web socket server has worked
43     // or not
44     private static final int CONNECTION_TRY_INTERVAL_MS = 100;
45
46     /**
47      * Constructor of this class, uses its {@link InternalMessageBusClient} superclass to set up the
48      * web socket and handle incoming message forwarding.
49      *
50      * @param serverUri The URI of the service
51      */
52     public MessagingClient(final URI serverUri) {
53         // Call the super class to create the web socket and set up received message forwarding
54         super(serverUri);
55     }
56
57     /*
58      * (non-Javadoc)
59      *
60      * @see org.onap.policy.apex.core.infrastructure.messaging.MessagingService#stopConnection()
61      */
62     @Override
63     public void stopConnection() {
64         // Stop message reception in the super class
65         super.stopListener();
66
67         // Close the web socket
68         final WebSocket connection = super.getConnection();
69         if (connection != null && connection.isOpen()) {
70             connection.closeConnection(0, "");
71         }
72         this.close();
73     }
74
75     /*
76      * (non-Javadoc)
77      *
78      * @see org.onap.policy.apex.core.infrastructure.messaging.MessagingService#startConnection()
79      */
80     @Override
81     public void startConnection() {
82         // Open the web socket
83         final WebSocket connection = super.getConnection();
84
85         if (connection == null) {
86             throw new IllegalStateException("Could not connect to the server");
87         }
88         if (!connection.isOpen()) {
89             connect();
90         }
91
92         if (!waitforConnection(connection)) {
93             throw new IllegalStateException("Could not connect to the server");
94         }
95     }
96
97     /**
98      * This method waits for the timeout value for the client to connect to the web socket server.
99      *
100      * @param connection the connection to wait on
101      * @return true, if successful
102      */
103     private boolean waitforConnection(final WebSocket connection) {
104         // The total time we have before timeout
105         int timeoutMsCounter = CONNECTION_TIMEOUT_TIME_MS;
106
107         // Check the connection state
108         do {
109             switch (connection.getReadyState()) {
110                 case NOT_YET_CONNECTED:
111                 case CONNECTING:
112                 case CLOSING:
113                     // Not connected yet so wait for the try interval
114                     ThreadUtilities.sleep(CONNECTION_TRY_INTERVAL_MS);
115                     timeoutMsCounter -= CONNECTION_TRY_INTERVAL_MS;
116                     break;
117                 case OPEN:
118                     // Connection is open, happy days
119                     return true;
120                 case CLOSED:
121                     // Connection is closed, bah
122                     return false;
123                 default:
124                     break;
125             }
126         }
127         // While the timeout value has not expired
128         while (timeoutMsCounter > 0);
129
130         // We have timed out
131         return false;
132     }
133
134     /*
135      * (non-Javadoc)
136      *
137      * @see
138      * org.onap.policy.apex.core.infrastructure.messaging.MessagingService#send(org.onap.policy.apex
139      * .core. infrastructure. messaging.MessageHolder)
140      */
141     @Override
142     public void send(final MessageHolder<M> commands) {
143         // Get the connection and send the message
144         final WebSocket connection = super.getConnection();
145         connection.send(MessagingUtils.serializeObject(commands));
146     }
147
148     /*
149      * (non-Javadoc)
150      *
151      * @see
152      * org.onap.policy.apex.core.infrastructure.messaging.MessagingService#send(java.lang.String)
153      */
154     @Override
155     public void send(final String messageString) {
156         final WebSocket connection = super.getConnection();
157         connection.send(messageString);
158     }
159
160     /*
161      * (non-Javadoc)
162      *
163      * @see org.onap.policy.apex.core.infrastructure.messaging.MessagingService#isStarted()
164      */
165     @Override
166     public boolean isStarted() {
167         return getConnection().isOpen();
168     }
169 }