5b2167e757a646b5bba70d7257c6e3e932229050
[policy/apex-pdp.git] / core / core-infrastructure / src / main / java / org / onap / policy / apex / core / infrastructure / messaging / impl / ws / server / MessageServerImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2020 Nordix Foundation.
5  * ================================================================================
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.apex.core.infrastructure.messaging.impl.ws.server;
23
24 import java.io.IOException;
25 import java.net.InetSocketAddress;
26 import java.util.Collection;
27 import java.util.concurrent.atomic.AtomicBoolean;
28
29 import org.java_websocket.WebSocket;
30 import org.onap.policy.apex.core.infrastructure.messaging.MessageHolder;
31 import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils;
32 import org.slf4j.ext.XLogger;
33 import org.slf4j.ext.XLoggerFactory;
34
35 /**
36  * A messaging server implementation using web socket.
37  *
38  * @author Sajeevan Achuthan (sajeevan.achuthan@ericsson.com)
39  * @param <M> the generic type of message being passed
40  */
41 public class MessageServerImpl<M> extends InternalMessageBusServer<M> {
42     // The logger for this class
43     private static final XLogger LOGGER = XLoggerFactory.getXLogger(MessageServerImpl.class);
44
45     // The Web Socket protocol for URIs and URLs
46     private static final String PROTOCOL = "ws://";
47
48     // URI of this server
49     private final String connectionUri;
50
51     // Indicates if the web socket server is started or not
52     private final AtomicBoolean isStarted = new AtomicBoolean(false);
53
54     /**
55      * Instantiates a new web socket messaging server for Apex.
56      *
57      * @param address the address of the server machine on which to start the server
58      */
59     public MessageServerImpl(final InetSocketAddress address) {
60         // Call the super class to create the web socket and set up received message forwarding
61         super(address);
62         LOGGER.entry(address);
63
64         // Compose the Web Socket URI
65         connectionUri = PROTOCOL + address.getHostString() + ":" + address.getPort();
66         LOGGER.debug("Server connection URI: {}", connectionUri);
67
68         LOGGER.exit();
69     }
70
71     /**
72      * {@inheritDoc}.
73      */
74     @Override
75     public void startConnection() {
76         // Start reception of connections on the web socket
77         start();
78     }
79
80     /**
81      * {@inheritDoc}.
82      */
83     @Override
84     public void stopConnection() {
85         // Stop message listening using our super class
86         stopListener();
87
88         // Stop the web socket server
89         try {
90             // Close all connections on this web socket server
91             for (final WebSocket connection : getConnections()) {
92                 connection.closeConnection(0, "");
93             }
94             stop();
95         } catch (final IOException ioe) {
96             LOGGER.catching(ioe);
97         } catch (final InterruptedException e) {
98             // restore the interrupt status
99             Thread.currentThread().interrupt();
100             // This can happen in normal operation so ignore
101         }
102         isStarted.set(false);
103     }
104
105     /**
106      * Return the current connection URI.
107      *
108      * @return connection URI
109      */
110     public String getConnectionUrl() {
111         if (connectionUri == null) {
112             throw new IllegalStateException("URI not set - The server is not started");
113         }
114         return connectionUri;
115     }
116
117     /**
118      * {@inheritDoc}.
119      */
120     @Override
121     public void send(final MessageHolder<M> message) {
122         // Send the incoming message to all clients connected to this web socket
123         final Collection<WebSocket> connections = getConnections();
124         for (final WebSocket webSocket : connections) {
125             webSocket.send(MessagingUtils.serializeObject(message));
126         }
127     }
128
129     /**
130      * {@inheritDoc}.
131      */
132     @Override
133     public void send(final String messageString) {
134         final Collection<WebSocket> connections = getConnections();
135         for (final WebSocket webSocket : connections) {
136             webSocket.send(messageString);
137         }
138     }
139
140     /**
141      * {@inheritDoc}.
142      */
143     @Override
144     public boolean isStarted() {
145         return isStarted.get();
146     }
147
148     @Override
149     public void onStart() {
150         isStarted.set(true);
151         LOGGER.debug("started deployment server on URI: {}", connectionUri);
152     }
153 }