6b1dc67092e0364141baefa84469ecb461378a88
[policy/apex-pdp.git] / core / core-infrastructure / src / main / java / org / onap / policy / apex / core / infrastructure / messaging / stringmessaging / WsStringMessageServer.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2016-2018 Ericsson. All rights reserved.
4  *  Modifications Copyright (C) 2019-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.stringmessaging;
23
24 import com.google.common.eventbus.Subscribe;
25
26 import java.net.InetAddress;
27 import java.net.InetSocketAddress;
28 import java.net.UnknownHostException;
29
30 import org.onap.policy.apex.core.infrastructure.messaging.MessageListener;
31 import org.onap.policy.apex.core.infrastructure.messaging.MessagingException;
32 import org.onap.policy.apex.core.infrastructure.messaging.MessagingService;
33 import org.onap.policy.apex.core.infrastructure.messaging.MessagingServiceFactory;
34 import org.onap.policy.apex.core.infrastructure.messaging.impl.ws.messageblock.MessageBlock;
35 import org.onap.policy.apex.core.infrastructure.messaging.util.MessagingUtils;
36 import org.slf4j.ext.XLogger;
37 import org.slf4j.ext.XLoggerFactory;
38
39 /**
40  * This class runs a web socket server for sending and receiving of strings over a web socket.
41  *
42  * @author Liam Fallon (liam.fallon@ericsson.com)
43  */
44 public class WsStringMessageServer implements WsStringMessager {
45     private static final XLogger LOGGER = XLoggerFactory.getXLogger(WsStringMessageServer.class);
46
47     // Message service factory and the message service itself
48     private final MessagingServiceFactory<String> factory = new MessagingServiceFactory<>();
49     private MessagingService<String> service = null;
50
51     // The listener to use for reception of strings
52     private WsStringMessageListener wsStringMessageListener;
53
54     // Address of the server
55     private final int port;
56
57     /**
58      * Constructor, define the port of the server.
59      *
60      * @param port the port of the server
61      */
62     public WsStringMessageServer(final int port) {
63         this.port = port;
64     }
65
66     /**
67      * {@inheritDoc}.
68      */
69     @Override
70     public void start(final WsStringMessageListener newWsStringMessageListener) throws MessagingException {
71
72         LOGGER.entry("web socket event consumer server starting . . .");
73         if (LOGGER.isDebugEnabled()) {
74             String lanaddress = "unknown";
75             try {
76                 lanaddress = MessagingUtils.getLocalHostLanAddress().getHostAddress();
77             } catch (final UnknownHostException ignore) {
78                 LOGGER.debug("Failed to find name of local address name", ignore);
79             }
80             LOGGER.debug("web socket string message server LAN address=" + lanaddress);
81             String hostaddress = "unknown";
82             try {
83                 hostaddress = InetAddress.getLocalHost().getHostAddress();
84             } catch (final UnknownHostException ignore) {
85                 LOGGER.debug("Failed to find name of local address", ignore);
86             }
87             LOGGER.debug("web socket string message server host address=" + hostaddress);
88         }
89
90         this.wsStringMessageListener = newWsStringMessageListener;
91
92         try {
93             service = factory.createServer(new InetSocketAddress(port));
94             service.addMessageListener(new WsStringMessageServerListener());
95             service.startConnection();
96         } catch (final Exception e) {
97             LOGGER.warn("web socket string message server start failed", e);
98             throw new MessagingException("web socket string message start failed", e);
99         }
100
101         LOGGER.exit("web socket string message server started");
102     }
103
104     /**
105      * {@inheritDoc}.
106      */
107     @Override
108     public void stop() {
109         LOGGER.entry("web socket string message server stopping . . .");
110         service.stopConnection();
111         LOGGER.exit("web socket string message server stopped");
112     }
113
114     /**
115      * {@inheritDoc}.
116      */
117     @Override
118     public void sendString(final String stringMessage) {
119         service.send(stringMessage);
120         if (LOGGER.isDebugEnabled()) {
121             LOGGER.debug("server sent message: {}", stringMessage);
122         }
123     }
124
125     /**
126      * The listener for strings coming into the server.
127      */
128     private class WsStringMessageServerListener implements MessageListener<String> {
129
130         /**
131          * {@inheritDoc}.
132          */
133         @Subscribe
134         @Override
135         public void onMessage(final MessageBlock<String> messageBlock) {
136             throw new UnsupportedOperationException("raw messages are not supported on string message clients");
137         }
138
139         /**
140          * {@inheritDoc}.
141          */
142         @Subscribe
143         @Override
144         public void onMessage(final String messageString) {
145             wsStringMessageListener.receiveString(messageString);
146         }
147     }
148
149     /**
150      * {@inheritDoc}.
151      */
152     @Override
153     public boolean isStarted() {
154         return service.isStarted();
155     }
156 }