2 * ============LICENSE_START========================================================================
3 * ONAP : ccsdk feature sdnr wt
4 * =================================================================================================
5 * Copyright (C) 2019 highstreet technologies GmbH Intellectual Property. All rights reserved.
6 * =================================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
8 * in compliance with the License. You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software distributed under the License
13 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
14 * or implied. See the License for the specific language governing permissions and limitations under
16 * ============LICENSE_END==========================================================================
18 package org.onap.ccsdk.features.sdnr.wt.websocketmanager;
20 import com.fasterxml.jackson.core.JsonProcessingException;
21 import java.security.SecureRandom;
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.Map.Entry;
28 import java.util.concurrent.ArrayBlockingQueue;
29 import java.util.concurrent.ExecutionException;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.TimeoutException;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34 import org.eclipse.jetty.websocket.api.Session;
35 import org.eclipse.jetty.websocket.api.WebSocketAdapter;
36 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.DOMNotificationOutput;
37 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.INotificationOutput;
38 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.NotificationOutput;
39 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.ReducedSchemaInfo;
40 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.ScopeRegistration;
41 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.ScopeRegistration.DataType;
42 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.ScopeRegistrationResponse;
43 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.utils.UserScopes;
44 import org.onap.ccsdk.features.sdnr.wt.yang.mapper.YangToolsMapper;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 public class WebSocketManagerSocket extends WebSocketAdapter {
50 private static final Logger LOG = LoggerFactory.getLogger(WebSocketManagerSocket.class);
51 public static final String MSG_KEY_DATA = "data";
52 public static final DataType MSG_KEY_SCOPES = DataType.scopes;
53 public static final String MSG_KEY_PARAM = "param";
54 public static final String MSG_KEY_VALUE = "value";
55 public static final String MSG_KEY_SCOPE = "scope";
57 public static final String KEY_NODEID = "nodeId";
58 public static final String KEY_EVENTTYPE = "eventType";
59 private static final String REGEX_SCOPEREGISTRATION = "\"data\"[\\s]*:[\\s]*\"scopes\"";
60 private static final Pattern PATTERN_SCOPEREGISTRATION =
61 Pattern.compile(REGEX_SCOPEREGISTRATION, Pattern.MULTILINE);
62 private static final SecureRandom RND = new SecureRandom();
63 private static final long SEND_MESSAGE_TIMEOUT_MILLIS = 1500;
64 private static final int QUEUE_SIZE = 100;
66 private final Thread sendingSyncThread;
67 private final ArrayBlockingQueue<String> messageQueue;
68 private boolean closed;
70 private final Runnable sendingRunner = new Runnable() {
73 LOG.debug("isrunning");
77 String message = messageQueue.poll();
78 if (message != null) {
79 WebSocketManagerSocket.this.session.getRemote().sendStringByFuture(message)
80 .get(SEND_MESSAGE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
81 LOG.debug("message sent");
83 } catch (ExecutionException | TimeoutException e) {
84 LOG.warn("problem pushing message: ", e);
85 } catch (InterruptedException e) {
86 LOG.warn("Interrupted!", e);
87 // Restore interrupted state...
88 Thread.currentThread().interrupt();
91 if (messageQueue.isEmpty()) {
96 LOG.debug("isstopped");
101 private static void trySleep(int sleepMs) {
103 Thread.sleep(sleepMs);
104 } catch (InterruptedException e) {
105 Thread.currentThread().interrupt();
110 * list of all sessionids
112 private static final List<String> sessionIds = new ArrayList<>();
114 * map of sessionid <=> UserScopes
116 private static final HashMap<String, UserScopes> userScopesList = new HashMap<>();
118 * map of class.hashCode <=> class
120 private static final HashMap<String, WebSocketManagerSocket> clientList = new HashMap<>();
122 private static final YangToolsMapper mapper = new YangToolsMapper();
123 private final String myUniqueSessionId;
125 private Session session = null;
127 public interface EventInputCallback {
128 void onMessagePushed(final String message) throws Exception;
131 public WebSocketManagerSocket() {
132 this.myUniqueSessionId = _genSessionId();
133 this.sendingSyncThread = new Thread(this.sendingRunner);
134 this.messageQueue = new ArrayBlockingQueue<>(QUEUE_SIZE);
138 protected void finalize() throws Throwable {
139 sessionIds.remove(this.myUniqueSessionId);
142 private static String _genSessionId() {
143 String sid = String.valueOf(RND.nextLong());
144 while (sessionIds.contains(sid)) {
145 sid = String.valueOf(RND.nextLong());
152 public void onWebSocketText(String message) {
153 LOG.debug("{} has sent {}", this.getRemoteAdr(), message);
154 if (!this.manageClientRequest(message)) {
155 this.manageClientRequest2(message);
160 public void onWebSocketBinary(byte[] payload, int offset, int len) {
161 LOG.debug("Binary not supported");
165 public void onWebSocketConnect(Session sess) {
168 this.sendingSyncThread.start();
169 clientList.put(String.valueOf(this.hashCode()), this);
170 LOG.debug("client connected from {}", this.getRemoteAdr());
174 public void onWebSocketClose(int statusCode, String reason) {
175 clientList.remove(String.valueOf(this.hashCode()));
176 this.sendingSyncThread.interrupt();
178 LOG.debug("client disconnected from {}", this.getRemoteAdr());
182 public void onWebSocketError(Throwable cause) {
183 LOG.debug("error caused on {}: ",this.getRemoteAdr(), cause);
186 private String getRemoteAdr() {
187 String adr = "unknown";
189 adr = this.session.getRemoteAddress().toString();
190 } catch (Exception e) {
191 LOG.debug("error resolving adr: {}", e.getMessage());
198 * @param request is a json object {"data":"scopes","scopes":["scope1","scope2",...]}
201 private boolean manageClientRequest(String request) {
203 final Matcher matcher = PATTERN_SCOPEREGISTRATION.matcher(request);
204 if (!matcher.find()) {
208 ScopeRegistration registration = mapper.readValue(request, ScopeRegistration.class);
209 if (registration != null && registration.validate() && registration.isType(MSG_KEY_SCOPES)) {
211 String sessionId = this.getSessionId();
212 UserScopes clientDto = new UserScopes();
213 clientDto.setScopes(registration.getScopes());
214 userScopesList.put(sessionId, clientDto);
215 this.send(mapper.writeValueAsString(ScopeRegistrationResponse.success(registration.getScopes())));
218 } catch (JsonProcessingException e) {
219 LOG.warn("problem set scope: {}" ,e.getMessage());
221 this.send(mapper.writeValueAsString(ScopeRegistrationResponse.error(e.getMessage())));
222 } catch (JsonProcessingException e1) {
223 LOG.warn("problem sending error response via ws: ", e1);
230 * broadcast message to all your clients
232 private void manageClientRequest2(String request) {
234 NotificationOutput notification = mapper.readValue(request, NotificationOutput.class);
235 if (notification.getNodeId() != null && notification.getType() != null) {
236 this.sendToAll(notification.getNodeId(), notification.getType(), request);
238 } catch (Exception e) {
239 LOG.warn("handle ws request failed:",e);
243 public void send(String msg) {
245 LOG.trace("sending {}", msg);
246 this.messageQueue.put(msg);
247 } catch (InterruptedException e) {
248 LOG.warn("problem putting message into sending queue: {}", e.getMessage());
249 // Restore interrupted state...
250 Thread.currentThread().interrupt();
254 public String getSessionId() {
255 return this.myUniqueSessionId;
258 private void sendToAll(INotificationOutput output) {
260 sendToAll(output.getNodeId(), output.getType(), mapper.writeValueAsString(output));
261 } catch (JsonProcessingException e) {
262 LOG.warn("problem serializing noitifcation: ", e);
266 private void sendToAll(String nodeId, ReducedSchemaInfo reducedSchemaInfo, String notification) {
267 if (clientList.size() > 0) {
268 for (Map.Entry<String, WebSocketManagerSocket> entry : clientList.entrySet()) {
269 WebSocketManagerSocket socket = entry.getValue();
270 if (socket != null) {
272 UserScopes clientScopes = userScopesList.get(socket.getSessionId());
273 if (clientScopes != null) {
274 if (clientScopes.hasScope(nodeId, reducedSchemaInfo)) {
275 socket.send(notification);
277 LOG.debug("client has not scope {}", reducedSchemaInfo);
280 LOG.debug("no scopes for notifications registered");
282 } catch (Exception ioe) {
283 LOG.warn(ioe.getMessage());
286 LOG.debug("cannot broadcast. socket is null");
292 public static void broadCast(INotificationOutput output) {
293 if (clientList.size() > 0) {
294 Set<Entry<String, WebSocketManagerSocket>> e = clientList.entrySet();
295 WebSocketManagerSocket s = e.iterator().next().getValue();
302 public static void broadCast(DOMNotificationOutput domNotificationOutput) {
303 if (clientList.size() > 0) {
304 Set<Entry<String, WebSocketManagerSocket>> e = clientList.entrySet();
305 WebSocketManagerSocket s = e.iterator().next().getValue();
307 s.sendToAll(domNotificationOutput);