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.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.List;
25 import java.util.Map.Entry;
26 import java.util.Random;
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.NotificationOutput;
37 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.ReducedSchemaInfo;
38 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.ScopeRegistration;
39 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.ScopeRegistration.DataType;
40 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.model.data.ScopeRegistrationResponse;
41 import org.onap.ccsdk.features.sdnr.wt.websocketmanager.utils.UserScopes;
42 import org.onap.ccsdk.features.sdnr.wt.yang.mapper.YangToolsMapper;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 public class WebSocketManagerSocket extends WebSocketAdapter {
48 private static final Logger LOG = LoggerFactory.getLogger(WebSocketManagerSocket.class);
49 public static final String MSG_KEY_DATA = "data";
50 public static final DataType MSG_KEY_SCOPES = DataType.scopes;
51 public static final String MSG_KEY_PARAM = "param";
52 public static final String MSG_KEY_VALUE = "value";
53 public static final String MSG_KEY_SCOPE = "scope";
55 public static final String KEY_NODEID = "nodeId";
56 public static final String KEY_EVENTTYPE = "eventType";
57 private static final String REGEX_SCOPEREGISTRATION = "\"data\"[\\s]*:[\\s]*\"scopes\"";
58 private static final Pattern PATTERN_SCOPEREGISTRATION =
59 Pattern.compile(REGEX_SCOPEREGISTRATION, Pattern.MULTILINE);
60 private static final Random RND = new Random();
61 private static final long SEND_MESSAGE_TIMEOUT_MILLIS = 1500;
62 private static final int QUEUE_SIZE = 100;
64 private final Thread sendingSyncThread;
65 private final ArrayBlockingQueue<String> messageQueue;
66 private boolean closed;
68 private final Runnable sendingRunner = new Runnable() {
71 LOG.debug("isrunning");
75 String message = messageQueue.poll();
76 if (message != null) {
77 WebSocketManagerSocket.this.session.getRemote().sendStringByFuture(message)
78 .get(SEND_MESSAGE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS);
79 LOG.info("message sent");
81 } catch (InterruptedException | ExecutionException | TimeoutException e) {
82 LOG.warn("problem pushing message: ", e);
85 if (messageQueue.isEmpty()) {
90 LOG.debug("isstopped");
95 private static void trySleep(int sleepMs) {
97 Thread.sleep(sleepMs);
98 } catch (InterruptedException e) {
99 Thread.currentThread().interrupt();
104 * list of all sessionids
106 private static final List<String> sessionIds = new ArrayList<>();
108 * map of sessionid <=> UserScopes
110 private static final HashMap<String, UserScopes> userScopesList = new HashMap<>();
112 * map of class.hashCode <=> class
114 private static final HashMap<String, WebSocketManagerSocket> clientList = new HashMap<>();
116 private static final YangToolsMapper mapper = new YangToolsMapper();
117 private final String myUniqueSessionId;
119 private Session session = null;
121 public interface EventInputCallback {
122 void onMessagePushed(final String message) throws Exception;
125 public WebSocketManagerSocket() {
126 this.myUniqueSessionId = _genSessionId();
127 this.sendingSyncThread = new Thread(this.sendingRunner);
128 this.messageQueue = new ArrayBlockingQueue<>(QUEUE_SIZE);
132 protected void finalize() throws Throwable {
133 sessionIds.remove(this.myUniqueSessionId);
136 private static String _genSessionId() {
137 String sid = String.valueOf(RND.nextLong());
138 while (sessionIds.contains(sid)) {
139 sid = String.valueOf(RND.nextLong());
146 public void onWebSocketText(String message) {
147 LOG.info("{} has sent {}", this.getRemoteAdr(), message);
148 if (!this.manageClientRequest(message)) {
149 this.manageClientRequest2(message);
154 public void onWebSocketBinary(byte[] payload, int offset, int len) {
155 LOG.debug("Binary not supported");
159 public void onWebSocketConnect(Session sess) {
162 this.sendingSyncThread.start();
163 clientList.put(String.valueOf(this.hashCode()), this);
164 LOG.debug("client connected from " + this.getRemoteAdr());
168 public void onWebSocketClose(int statusCode, String reason) {
169 clientList.remove(String.valueOf(this.hashCode()));
170 this.sendingSyncThread.interrupt();
172 LOG.debug("client disconnected from " + this.getRemoteAdr());
176 public void onWebSocketError(Throwable cause) {
177 LOG.debug("error caused on " + this.getRemoteAdr() + " :" + cause.getMessage());
180 private String getRemoteAdr() {
181 String adr = "unknown";
183 adr = this.session.getRemoteAddress().toString();
184 } catch (Exception e) {
185 LOG.debug("error resolving adr: {}", e.getMessage());
192 * @param request is a json object {"data":"scopes","scopes":["scope1","scope2",...]}
195 private boolean manageClientRequest(String request) {
197 final Matcher matcher = PATTERN_SCOPEREGISTRATION.matcher(request);
198 if (!matcher.find()) {
202 ScopeRegistration registration = mapper.readValue(request, ScopeRegistration.class);
203 if (registration != null && registration.validate() && registration.isType(MSG_KEY_SCOPES)) {
205 String sessionId = this.getSessionId();
206 UserScopes clientDto = new UserScopes();
207 clientDto.setScopes(registration.getScopes());
208 userScopesList.put(sessionId, clientDto);
209 this.send(mapper.writeValueAsString(ScopeRegistrationResponse.success(registration.getScopes())));
212 } catch (JsonProcessingException e) {
213 LOG.warn("problem set scope: " + e.getMessage());
215 this.send(mapper.writeValueAsString(ScopeRegistrationResponse.error(e.getMessage())));
216 } catch (JsonProcessingException e1) {
217 LOG.warn("problem sending error response via ws: " + e1);
224 * broadcast message to all your clients
226 private void manageClientRequest2(String request) {
228 NotificationOutput notification = mapper.readValue(request, NotificationOutput.class);
229 if (notification.getNodeId() != null && notification.getType() != null) {
230 this.sendToAll(notification.getNodeId(), notification.getType(), request);
232 } catch (Exception e) {
233 LOG.warn("handle ws request failed:" + e.getMessage());
237 public void send(String msg) {
239 LOG.trace("sending {}", msg);
240 this.messageQueue.put(msg);
241 } catch (InterruptedException e) {
242 LOG.warn("problem putting message into sending queue: " + e.getMessage());
246 public String getSessionId() {
247 return this.myUniqueSessionId;
250 private void sendToAll(NotificationOutput output) {
252 sendToAll(output.getNodeId(), output.getType(), mapper.writeValueAsString(output));
253 } catch (JsonProcessingException e) {
254 LOG.warn("problem serializing noitifcation: ", e);
258 private void sendToAll(String nodeId, ReducedSchemaInfo reducedSchemaInfo, String notification) {
259 if (clientList.size() > 0) {
260 for (Map.Entry<String, WebSocketManagerSocket> entry : clientList.entrySet()) {
261 WebSocketManagerSocket socket = entry.getValue();
262 if (socket != null) {
264 UserScopes clientScopes = userScopesList.get(socket.getSessionId());
265 if (clientScopes != null) {
266 if (clientScopes.hasScope(nodeId, reducedSchemaInfo)) {
267 socket.send(notification);
269 LOG.debug("client has not scope {}", reducedSchemaInfo);
272 LOG.debug("no scopes for notifications registered");
274 } catch (Exception ioe) {
275 LOG.warn(ioe.getMessage());
278 LOG.debug("cannot broadcast. socket is null");
284 public static void broadCast(NotificationOutput output) {
285 if (clientList.size() > 0) {
286 Set<Entry<String, WebSocketManagerSocket>> e = clientList.entrySet();
287 WebSocketManagerSocket s = e.iterator().next().getValue();