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.Map.Entry;
25 import java.util.Random;
28 import org.eclipse.jetty.websocket.api.Session;
29 import org.eclipse.jetty.websocket.api.WebSocketAdapter;
30 import org.json.JSONObject;
31 import org.onap.ccsdk.features.sdnr.wt.websocketmanager2.utils.UserScopes;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
35 public class WebSocketManagerSocket extends WebSocketAdapter {
37 private static final Logger LOG = LoggerFactory.getLogger(WebSocketManagerSocket.class.getName());
38 public static final String MSG_KEY_DATA = "data";
39 public static final String MSG_KEY_SCOPES = "scopes";
40 public static final String MSG_KEY_PARAM = "param";
41 public static final String MSG_KEY_VALUE = "value";
42 public static final String MSG_KEY_SCOPE = "scope";
44 public static final String KEY_NODENAME = "nodename";
45 public static final String KEY_EVENTTYPE = "eventtype";
46 public static final String KEY_XMLEVENT = "xmlevent";
48 private static final Random RND = new Random();
52 * list of all sessionids
54 private static final List<String> sessionIds = new ArrayList<>();
56 * map of sessionid <=> UserScopes
58 private static final HashMap<String, UserScopes> userScopesList = new HashMap<>();
60 * map of class.hashCode <=> class
62 private static final HashMap<String, WebSocketManagerSocket> clientList = new HashMap<>();
63 private final String myUniqueSessionId;
65 private Session session = null;
67 public interface EventInputCallback {
68 void onMessagePushed(final String message) throws Exception;
71 public WebSocketManagerSocket() {
72 this.myUniqueSessionId = _genSessionId();
76 protected void finalize() throws Throwable {
77 sessionIds.remove(this.myUniqueSessionId);
80 private static String _genSessionId() {
81 String sid = String.valueOf(RND.nextLong());
82 while (sessionIds.contains(sid)) {
83 sid = String.valueOf(RND.nextLong());
90 public void onWebSocketText(String message) {
91 LOG.info("{} has sent {}",this.getRemoteAdr(), message);
92 if (!this.manageClientRequest(message)) {
93 this.manageClientRequest2(message);
98 public void onWebSocketBinary(byte[] payload, int offset, int len) {
99 LOG.debug("Binary not supported");
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) {
117 LOG.debug("error caused on " + this.getRemoteAdr() + " :" + cause.getMessage());
118 // super.onWebSocketError(cause);
121 private String getRemoteAdr() {
122 String adr = "unknown";
124 adr = this.session.getRemoteAddress().toString();
125 } catch (Exception e) {
126 LOG.debug("error resolving adr: {}", e.getMessage());
133 * @param request is a json object
134 * {"data":"scopes","scopes":["scope1","scope2",...]}
137 private boolean manageClientRequest(String request) {
140 JSONObject jsonMessage = new JSONObject(request);
141 if (jsonMessage.has(MSG_KEY_DATA)) {
142 String data = jsonMessage.getString(MSG_KEY_DATA);
143 if (data.equals(MSG_KEY_SCOPES)) {
145 String sessionId = this.getSessionId();
146 UserScopes clientDto = new UserScopes();
147 clientDto.setScopes(jsonMessage.getJSONArray(MSG_KEY_SCOPES));
148 userScopesList.put(sessionId, clientDto);
150 "You are connected to the Opendaylight Websocket server and scopes are : " + request + "");
153 } catch (Exception e) {
154 LOG.warn("problem set scope: " + e.getMessage());
155 this.send("Your request to the Opendaylight Websocket server is >> " + request
156 + " << which failed because of following exception >> " + e.toString());
162 * broadcast message to all your clients
164 private void manageClientRequest2(String request) {
166 JSONObject o = new JSONObject(request);
167 if (o.has(KEY_NODENAME) && o.has(KEY_EVENTTYPE)) {
168 this.sendToAll(o.getString(KEY_NODENAME), o.getString(KEY_EVENTTYPE), o.getString(KEY_XMLEVENT));
170 } catch (Exception e) {
171 LOG.warn("handle ws request failed:" + e.getMessage());
175 public void send(String msg) {
177 LOG.trace("sending {}", msg);
178 this.session.getRemote().sendString(msg);
179 } catch (Exception e) {
180 LOG.warn("problem sending message: " + e.getMessage());
183 public String getSessionId() {
184 return this.myUniqueSessionId;
187 private void sendToAll(String nodeName, String eventType, String xmlEvent) {
188 if (clientList.size() > 0) {
189 for (Map.Entry<String, WebSocketManagerSocket> entry : clientList.entrySet()) {
190 WebSocketManagerSocket socket = entry.getValue();
191 if (socket != null) {
193 UserScopes clientScopes = userScopesList.get(socket.getSessionId());
194 if (clientScopes != null) {
195 if (clientScopes.hasScope(eventType)) {
196 socket.send(xmlEvent);
198 LOG.debug("client has not scope {}", eventType);
201 LOG.debug("no scopes for notifications registered");
203 } catch (Exception ioe) {
204 LOG.warn(ioe.getMessage());
207 LOG.debug("cannot broadcast. socket is null");
212 public static void broadCast(String nodeName, String eventType, String xmlEvent) {
213 if(clientList.size()>0) {
214 Set<Entry<String, WebSocketManagerSocket>> e = clientList.entrySet();
215 WebSocketManagerSocket s = e.iterator().next().getValue();
218 s.sendToAll(nodeName, eventType, xmlEvent);