1 /*******************************************************************************
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==========================================================================
17 ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.websocketmanager2;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.List;
24 import java.util.Random;
26 import org.eclipse.jetty.websocket.api.Session;
27 import org.eclipse.jetty.websocket.api.WebSocketAdapter;
28 import org.json.JSONObject;
29 import org.onap.ccsdk.features.sdnr.wt.websocketmanager2.utils.UserScopes;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
33 public class WebSocketManagerSocket extends WebSocketAdapter {
35 private static final Logger LOG = LoggerFactory.getLogger(WebSocketManagerSocket.class.getName());
37 public static final String MSG_KEY_DATA = "data";
38 public static final String MSG_KEY_SCOPES = "scopes";
39 public static final String MSG_KEY_PARAM = "param";
40 public static final String MSG_KEY_VALUE = "value";
41 public static final String MSG_KEY_SCOPE = "scope";
43 public static final String KEY_NODENAME = "nodename";
44 public static final String KEY_EVENTTYPE = "eventtype";
45 public static final String KEY_XMLEVENT = "xmlevent";
47 private static final Random RND = new Random();
51 * list of all sessionids
53 private static final List<String> sessionIds = new ArrayList<>();
55 * map of sessionid <=> UserScopes
57 private static final HashMap<String, UserScopes> userScopesList = new HashMap<>();
59 * map of class.hashCode <=> class
61 private static final HashMap<String, WebSocketManagerSocket> clientList = new HashMap<>();
62 private final String myUniqueSessionId;
64 private Session session = null;
66 public interface EventInputCallback {
67 void onMessagePushed(final String message) throws Exception;
70 public WebSocketManagerSocket() {
71 this.myUniqueSessionId = _genSessionId();
75 protected void finalize() throws Throwable {
76 sessionIds.remove(this.myUniqueSessionId);
79 private static String _genSessionId() {
80 String sid = String.valueOf(RND.nextLong());
81 while (sessionIds.contains(sid)) {
82 sid = String.valueOf(RND.nextLong());
89 public void onWebSocketText(String message) {
90 LOG.info(this.getRemoteAdr() + " has sent " + message);
91 if (!this.manageClientRequest(message)) {
92 this.manageClientRequest2(message);
98 public void onWebSocketBinary(byte[] payload, int offset, int len) {
103 public void onWebSocketConnect(Session sess) {
105 clientList.put(String.valueOf(this.hashCode()), this);
106 LOG.debug("client connected from " + this.getRemoteAdr());
110 public void onWebSocketClose(int statusCode, String reason) {
111 clientList.remove(String.valueOf(this.hashCode()));
112 LOG.debug("client disconnected from " + this.getRemoteAdr());
116 public void onWebSocketError(Throwable cause) {
118 LOG.debug("error caused on " + this.getRemoteAdr() + " :" + cause.getMessage());
119 // super.onWebSocketError(cause);
122 private String getRemoteAdr() {
123 String adr = "unknown";
125 adr = this.session.getRemoteAddress().toString();
126 } catch (Exception e) {
127 LOG.debug("error resolving adr: {}", e.getMessage());
134 * @param request is a json object
135 * {"data":"scopes","scopes":["scope1","scope2",...]}
138 private boolean manageClientRequest(String request) {
141 JSONObject jsonMessage = new JSONObject(request);
142 if (jsonMessage.has(MSG_KEY_DATA)) {
143 String data = jsonMessage.getString(MSG_KEY_DATA);
144 if (data.equals(MSG_KEY_SCOPES)) {
146 String sessionId = this.getSessionId();
147 UserScopes clientDto = new UserScopes();
148 clientDto.setScopes(jsonMessage.getJSONArray(MSG_KEY_SCOPES));
149 userScopesList.put(sessionId, clientDto);
151 "You are connected to the Opendaylight Websocket server and scopes are : " + request + "");
154 } catch (Exception e) {
155 LOG.warn("problem set scope: " + e.getMessage());
156 this.send("Your request to the Opendaylight Websocket server is >> " + request
157 + " << which failed because of following exception >> " + e.toString());
163 * broadcast message to all your clients
165 private void manageClientRequest2(String request) {
167 JSONObject o = new JSONObject(request);
168 if (o.has(KEY_NODENAME) && o.has(KEY_EVENTTYPE)) {
169 broadCast(o.getString(KEY_NODENAME), o.getString(KEY_EVENTTYPE), o.getString(KEY_XMLEVENT));
171 } catch (Exception e) {
172 LOG.warn("handle ws request failed:" + e.getMessage());
176 private void send(String msg) {
178 LOG.trace("sending {}", msg);
179 this.session.getRemote().sendString(msg);
180 } catch (Exception e) {
181 LOG.warn("problem sending message: " + e.getMessage());
185 private String getSessionId() {
186 return this.myUniqueSessionId;
189 public static void broadCast(String nodeName, String eventType, String xmlEvent) {
190 if (clientList != null && clientList.size() > 0) {
191 for (Map.Entry<String, WebSocketManagerSocket> entry : clientList.entrySet()) {
192 WebSocketManagerSocket socket = entry.getValue();
193 if (socket != null) {
196 UserScopes clientScopes = userScopesList.get(socket.getSessionId());
197 if (clientScopes != null) {
198 if (clientScopes.hasScope(eventType)) {
199 socket.send(xmlEvent);
201 LOG.debug("client has not scope {}", eventType);
204 LOG.debug("no scopes for notifications registered");
206 } catch (Exception ioe) {
207 LOG.warn(ioe.getMessage());
210 LOG.debug("cannot broadcast. socket is null");