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