f445bcd23dc8d6ca8460554e42a2b5573f05dde1
[ccsdk/features.git] /
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
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
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
15  * the License.
16  * ============LICENSE_END==========================================================================
17  ******************************************************************************/
18 package org.onap.ccsdk.features.sdnr.wt.websocketmanager2;
19
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Random;
25
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;
32
33 public class WebSocketManagerSocket extends WebSocketAdapter {
34
35     private static final Logger LOG = LoggerFactory.getLogger(WebSocketManagerSocket.class.getName());
36
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";
42
43     public static final String KEY_NODENAME = "nodename";
44     public static final String KEY_EVENTTYPE = "eventtype";
45     public static final String KEY_XMLEVENT = "xmlevent";
46
47     private static final Random RND = new Random();
48
49
50     /**
51      * list of all sessionids
52      */
53     private static final List<String> sessionIds = new ArrayList<>();
54     /**
55      * map of sessionid <=> UserScopes
56      */
57     private static final HashMap<String, UserScopes> userScopesList = new HashMap<>();
58     /**
59      * map of class.hashCode <=> class
60      */
61     private static final HashMap<String, WebSocketManagerSocket> clientList = new HashMap<>();
62     private final String myUniqueSessionId;
63
64     private Session session = null;
65
66     public interface EventInputCallback {
67         void onMessagePushed(final String message) throws Exception;
68     }
69
70     public WebSocketManagerSocket() {
71         this.myUniqueSessionId = _genSessionId();
72     }
73
74     @Override
75     protected void finalize() throws Throwable {
76         sessionIds.remove(this.myUniqueSessionId);
77     }
78
79     private static String _genSessionId() {
80         String sid = String.valueOf(RND.nextLong());
81         while (sessionIds.contains(sid)) {
82             sid = String.valueOf(RND.nextLong());
83         }
84         sessionIds.add(sid);
85         return sid;
86     }
87
88     @Override
89     public void onWebSocketText(String message) {
90         LOG.info(this.getRemoteAdr() + " has sent " + message);
91         if (!this.manageClientRequest(message)) {
92             this.manageClientRequest2(message);
93         }
94
95     }
96
97     @Override
98     public void onWebSocketBinary(byte[] payload, int offset, int len) {
99
100     }
101
102     @Override
103     public void onWebSocketConnect(Session sess) {
104         this.session = sess;
105         clientList.put(String.valueOf(this.hashCode()), this);
106         LOG.debug("client connected from " + this.getRemoteAdr());
107     }
108
109     @Override
110     public void onWebSocketClose(int statusCode, String reason) {
111         clientList.remove(String.valueOf(this.hashCode()));
112         LOG.debug("client disconnected from " + this.getRemoteAdr());
113     }
114
115     @Override
116     public void onWebSocketError(Throwable cause) {
117
118         LOG.debug("error caused on " + this.getRemoteAdr() + " :" + cause.getMessage());
119         // super.onWebSocketError(cause);
120     }
121
122     private String getRemoteAdr() {
123         String adr = "unknown";
124         try {
125             adr = this.session.getRemoteAddress().toString();
126         } catch (Exception e) {
127             LOG.debug("error resolving adr: {}", e.getMessage());
128         }
129         return adr;
130     }
131
132     /**
133      *
134      * @param request is a json object
135      *                {"data":"scopes","scopes":["scope1","scope2",...]}
136      * @return if handled
137      */
138     private boolean manageClientRequest(String request) {
139         boolean ret = false;
140         try {
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)) {
145                     ret = true;
146                     String sessionId = this.getSessionId();
147                     UserScopes clientDto = new UserScopes();
148                     clientDto.setScopes(jsonMessage.getJSONArray(MSG_KEY_SCOPES));
149                     userScopesList.put(sessionId, clientDto);
150                     this.send(
151                             "You are connected to the Opendaylight Websocket server and scopes are : " + request + "");
152                 }
153             }
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());
158         }
159         return ret;
160     }
161
162     /*
163      * broadcast message to all your clients
164      */
165     private void manageClientRequest2(String request) {
166         try {
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));
170             }
171         } catch (Exception e) {
172             LOG.warn("handle ws request failed:" + e.getMessage());
173         }
174     }
175
176     private void send(String msg) {
177         try {
178             LOG.trace("sending {}", msg);
179             this.session.getRemote().sendString(msg);
180         } catch (Exception e) {
181             LOG.warn("problem sending message: " + e.getMessage());
182         }
183     }
184
185     private String getSessionId() {
186         return this.myUniqueSessionId;
187     }
188
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) {
194                     try {
195
196                         UserScopes clientScopes = userScopesList.get(socket.getSessionId());
197                         if (clientScopes != null) {
198                             if (clientScopes.hasScope(eventType)) {
199                                 socket.send(xmlEvent);
200                             } else {
201                                 LOG.debug("client has not scope {}", eventType);
202                             }
203                         } else {
204                             LOG.debug("no scopes for notifications registered");
205                         }
206                     } catch (Exception ioe) {
207                         LOG.warn(ioe.getMessage());
208                     }
209                 } else {
210                     LOG.debug("cannot broadcast. socket is null");
211                 }
212             }
213         }
214     }
215
216 }