Remove insecure dependency on PolicyEngineAPI
[policy/engine.git] / PolicyEngineAPI / src / main / java / org / onap / policy / std / AutoClientEnd.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * PolicyEngineAPI
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.std;
22
23 import java.io.IOException;
24 import java.net.URI;
25
26 import javax.websocket.ClientEndpoint;
27 import javax.websocket.OnClose;
28 import javax.websocket.OnError;
29 import javax.websocket.OnMessage;
30 import javax.websocket.OnOpen;
31 import javax.websocket.Session;
32
33 import org.java_websocket.client.WebSocketClient;
34 import org.java_websocket.handshake.ServerHandshake;
35 import org.onap.policy.api.NotificationHandler;
36 import org.onap.policy.api.NotificationScheme;
37 import org.onap.policy.api.NotificationType;
38 import org.onap.policy.api.PDPNotification;
39 import org.onap.policy.common.logging.flexlogger.FlexLogger;
40 import org.onap.policy.common.logging.flexlogger.Logger;
41 import org.onap.policy.xacml.api.XACMLErrorConstants; 
42
43 @ClientEndpoint
44 public class AutoClientEnd extends WebSocketClient {
45         private static StdPDPNotification notification = null;
46         private static StdPDPNotification oldNotification = null;
47         private static AutoClientEnd client = null;
48         private static NotificationScheme scheme = null;
49         private static NotificationHandler handler = null;
50         private static String url = null;
51         private static Session session = null;
52         private static boolean status = false; 
53         private static boolean stop = false;
54         private static boolean message = false;
55         private static boolean error = false;
56         private static Logger logger = FlexLogger.getLogger(AutoClientEnd.class.getName());
57         
58         private AutoClientEnd(URI serverUri) {
59                 super(serverUri);
60         }
61
62         @Override
63         public void onClose(int arg0, String arg1, boolean arg2) {
64                 // Not implemented
65         }
66
67         @Override
68         public void onError(Exception arg0) {
69                 // Not implemented
70         }
71
72         @Override
73         public void onMessage(String arg0) {
74                 // Not implemented
75         }
76
77         @Override
78         public void onOpen(ServerHandshake arg0) {
79                 // Not implemented
80         }
81
82         public static void setAuto(NotificationScheme scheme,
83                         NotificationHandler handler) {
84                 AutoClientEnd.scheme = scheme;
85                 AutoClientEnd.handler = handler;
86         }
87
88         public static void setScheme(NotificationScheme scheme) {
89                 AutoClientEnd.scheme = scheme;
90         }
91         
92         public static boolean getStatus(){
93                 return AutoClientEnd.status;
94         }
95
96         public static String getURL() {
97                 return AutoClientEnd.url;
98         }
99
100         public static void start(String url) {
101                 AutoClientEnd.url = url;
102                 
103                 if (scheme == null || handler == null ||
104                         ! (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) ||
105                                         scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS) ) ||
106                         AutoClientEnd.client != null) {
107                         return;
108                 }
109
110                 if (url.contains("https")) {
111                         url = url.replaceAll("https", "wss");
112                 }
113                 else {
114                         url = url.replaceAll("http", "ws");
115                 }
116                 
117                 
118                 // Stop and Start needs to be done.
119                 try {
120                         logger.info("Starting Auto Notification with the PDP server : " + url);
121                         client = new AutoClientEnd(new URI(url  + "notifications"));
122                         status = true;
123                         if(error){
124                                 // The URL's will be in Sync according to design Spec. 
125                                 ManualClientEnd.start(AutoClientEnd.url);
126                                 StdPDPNotification notification = NotificationStore.getDeltaNotification((StdPDPNotification)ManualClientEnd.result(NotificationScheme.MANUAL_ALL_NOTIFICATIONS));
127                                 if(notification.getNotificationType()!=null&&oldNotification!=notification){
128                                     oldNotification= notification;
129                                     AutoClientEnd.notification = notification;
130                                     callHandler();
131                                 }
132                                 error = false;
133                         }
134                         //
135                 } catch (Exception e) {
136                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
137                         client = null;
138                         status = false;
139                         changeURL();
140                 }
141         }
142         
143         private static void changeURL(){
144                 // Change the PDP if it is not Up. 
145                 StdPolicyEngine.rotatePDPList();
146                 start(StdPolicyEngine.getPDPURL());
147         }
148
149         public static void stop() {
150                 if (client == null) {
151                         return;
152                 }
153                 client.close();
154                 if(session!=null){
155                         try {
156                                 stop = true;
157                                 logger.info("\n Closing Auto Notification WebSocket Connection.. ");
158                                 session.close();
159                                 session = null;
160                         } catch (IOException e) {
161                                 logger.error("Error closing websocket connection", e);
162                         }
163                 }
164                 client = null;
165                 status = false;
166                 stop = false;
167         }
168
169         private static void callHandler() {
170                 if (handler == null || scheme == null) {
171                         return;
172                 }
173                 if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)) {
174                         boolean removed = false;
175                         boolean updated = false;
176                         if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) {
177                                 removed = true;
178                         }
179                         if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) {
180                                 updated = true;
181                         }
182                         if (removed && updated) {
183                                 notification.setNotificationType(NotificationType.BOTH);
184                         } else if (removed) {
185                                 notification.setNotificationType(NotificationType.REMOVE);
186                         } else if (updated) {
187                                 notification.setNotificationType(NotificationType.UPDATE);
188                         }
189                         try{
190                                 handler.notificationReceived(notification);
191                         }catch (Exception e){
192                                 logger.error("Error in Clients Handler Object : ", e);
193                         }
194                 } else if (scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) {
195                         PDPNotification newNotification = MatchStore.checkMatch(notification);
196                         if (newNotification.getNotificationType() != null) {
197                                 try{
198                                         handler.notificationReceived(newNotification);
199                                 }catch (Exception e){
200                                         logger.error("Error in Clients Handler Object : ", e);
201                                 }
202                         }
203                 }
204         }
205
206         // WebSockets Code..
207         @OnOpen
208         public static void onOpen(Session session){
209                 logger.debug("Auto Notification Session Started... " + session.getId());
210                 if(AutoClientEnd.session == null){
211                         AutoClientEnd.session = session;
212                 }
213         }
214
215         @OnError
216         public static void onError(Session session, Throwable e) {
217                 // trying to Restart by self.
218                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error.. "+ session.getId() + "\n Error is : " + e );
219                 stop();
220                 if (url != null) {
221                         client = null;
222                         status = false;
223                         error= true;
224                         start(url);
225                 }
226         }
227
228         @OnClose
229         public static void onClose(Session session) {
230                 logger.info("Session ended with "+ session.getId());
231                 if(!stop && !message){
232                         // This Block of code is executed if there is any Network Failure or if the Notification is Down. 
233                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Disconnected from Notification Server");
234                         client = null;
235                         status = false;
236                         AutoClientEnd.session=null;
237                         // Try to connect Back to available PDP.
238                         error = true;
239                         start(url);
240                 }
241                 AutoClientEnd.message=false;
242         }
243
244         @OnMessage
245         public static void onMessage(String message, Session session) throws IOException {
246                 AutoClientEnd.message = true;
247                 logger.debug("Auto Notification Recieved Message " + message + " Session info is : " + session.getId());
248                 try {
249                         notification = NotificationUnMarshal.notificationJSON(message);
250                 } catch (Exception e) {
251                         logger.error("PE500 " + e);
252                 }
253                 if(AutoClientEnd.session == session){
254                         try{
255                                 NotificationStore.recordNotification(notification);
256                         }catch(Exception e){
257                                 logger.error(e);
258                         }
259                         if(oldNotification!=notification){
260                                 oldNotification= notification;
261                                 callHandler();
262                         }
263                 }else{
264                         session.close();
265                 }
266                 AutoClientEnd.message = false;
267         }
268 }