Fixes for sonar critical issues
[policy/engine.git] / PolicyEngineAPI / src / main / java / org / onap / policy / std / AutoClientEnd.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * PolicyEngineAPI
4  * ================================================================================
5  * Copyright (C) 2017 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 import java.net.URISyntaxException;
26
27 import javax.websocket.ClientEndpoint;
28 import javax.websocket.DeploymentException;
29 import javax.websocket.OnClose;
30 import javax.websocket.OnError;
31 import javax.websocket.OnMessage;
32 import javax.websocket.OnOpen;
33 import javax.websocket.Session;
34
35 import org.glassfish.tyrus.client.ClientManager;
36 import org.onap.policy.api.NotificationHandler;
37 import org.onap.policy.api.NotificationScheme;
38 import org.onap.policy.api.NotificationType;
39 import org.onap.policy.api.PDPNotification;
40 import org.onap.policy.common.logging.flexlogger.FlexLogger;
41 import org.onap.policy.common.logging.flexlogger.Logger;
42 import org.onap.policy.xacml.api.XACMLErrorConstants; 
43
44 @ClientEndpoint
45 public class AutoClientEnd {
46         private static StdPDPNotification notification = null;
47         private static StdPDPNotification oldNotification = null;
48         private static ClientManager client = null;
49         private static NotificationScheme scheme = null;
50         private static NotificationHandler handler = null;
51         private static String url = null;
52         private static Session session = null;
53         private static boolean status = false; 
54         private static boolean stop = false;
55         private static boolean message = false;
56         private static boolean error = false;
57         private static Logger logger = FlexLogger.getLogger(AutoClientEnd.class.getName());
58         
59         public static void setAuto(NotificationScheme scheme,
60                         NotificationHandler handler) {
61                 AutoClientEnd.scheme = scheme;
62                 AutoClientEnd.handler = handler;
63         }
64
65         public static void setScheme(NotificationScheme scheme) {
66                 AutoClientEnd.scheme = scheme;
67         }
68         
69         public static boolean getStatus(){
70                 return AutoClientEnd.status;
71         }
72
73         public static String getURL() {
74                 return AutoClientEnd.url;
75         }
76
77         public static void start(String url) {
78                 AutoClientEnd.url = url;
79                 // Stop and Start needs to be done.
80                 if (scheme != null && handler!=null) {
81                         if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) || scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) {
82                                 if (AutoClientEnd.client == null) {
83                                         client = ClientManager.createClient();
84                                         if(url.contains("https")){
85                                                 url = url.replaceAll("https", "wss");
86                                         }else {
87                                                 url = url.replaceAll("http", "ws");
88                                         }
89                                         try {
90                                                 logger.info("Starting Auto Notification with the PDP server : " + url);
91                                                 client.connectToServer(AutoClientEnd.class, new URI(url + "notifications"));
92                                                 status = true;
93                                                 if(error){
94                                                         // The URL's will be in Sync according to design Spec. 
95                                                         ManualClientEnd.start(AutoClientEnd.url);
96                                                         StdPDPNotification notification = NotificationStore.getDeltaNotification((StdPDPNotification)ManualClientEnd.result(NotificationScheme.MANUAL_ALL_NOTIFICATIONS));
97                                                         if(notification.getNotificationType()!=null&&oldNotification!=notification){
98                                                             oldNotification= notification;
99                                                             AutoClientEnd.notification = notification;
100                                                             callHandler();
101                                                         }
102                                                         error = false;
103                                                 }
104                                                 //
105                                         } catch (DeploymentException | IOException | URISyntaxException e) {
106                                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
107                                                 client = null;
108                                                 status = false;
109                                                 changeURL();
110                                         }
111                                 }
112                         }
113                 }
114         }
115         
116         private static void changeURL(){
117                 // Change the PDP if it is not Up. 
118                 StdPolicyEngine.rotatePDPList();
119                 start(StdPolicyEngine.getPDPURL());
120         }
121
122         public static void stop() {
123                 if (client != null) {
124                         client.shutdown();
125                         if(session!=null){
126                                 try {
127                                         stop = true;
128                                         logger.info("\n Closing Auto Notification WebSocket Connection.. ");
129                                         session.close();
130                                         session = null;
131                                 } catch (IOException e) {
132                                         logger.error("Error closing websocket connection", e);
133                                 }
134                         }
135                         client = null;
136                         status = false;
137                         stop = false;
138                 }
139         }
140
141         private static void callHandler() {
142                 if (handler != null && scheme != null) {
143                         if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)) {
144                                 boolean removed = false;
145                                 boolean updated = false;
146                                 if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) {
147                                         removed = true;
148                                 }
149                                 if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) {
150                                         updated = true;
151                                 }
152                                 if (removed && updated) {
153                                         notification.setNotificationType(NotificationType.BOTH);
154                                 } else if (removed) {
155                                         notification.setNotificationType(NotificationType.REMOVE);
156                                 } else if (updated) {
157                                         notification.setNotificationType(NotificationType.UPDATE);
158                                 }
159                                 try{
160                                         handler.notificationReceived(notification);
161                                 }catch (Exception e){
162                                         logger.error("Error in Clients Handler Object : ", e);
163                                 }
164                         } else if (scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) {
165                                 PDPNotification newNotification = MatchStore.checkMatch(notification);
166                                 if (newNotification.getNotificationType() != null) {
167                                         try{
168                                                 handler.notificationReceived(newNotification);
169                                         }catch (Exception e){
170                                                 logger.error("Error in Clients Handler Object : ", e);
171                                         }
172                                 }
173                         }
174                 }
175         }
176
177         // WebSockets Code..
178         @OnOpen
179         public static void onOpen(Session session){
180                 logger.debug("Auto Notification Session Started... " + session.getId());
181                 if(AutoClientEnd.session == null){
182                         AutoClientEnd.session = session;
183                 }
184         }
185
186         @OnError
187         public static void onError(Session session, Throwable e) {
188                 // trying to Restart by self.
189                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error.. "+ session.getId() + "\n Error is : " + e );
190                 stop();
191                 if (url != null) {
192                         client = null;
193                         status = false;
194                         error= true;
195                         start(url);
196                 }
197         }
198
199         @OnClose
200         public static void onClose(Session session) {
201                 logger.info("Session ended with "+ session.getId());
202                 if(!stop && !message){
203                         // This Block of code is executed if there is any Network Failure or if the Notification is Down. 
204                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Disconnected from Notification Server");
205                         client = null;
206                         status = false;
207                         AutoClientEnd.session=null;
208                         // Try to connect Back to available PDP.
209                         error = true;
210                         start(url);
211                 }
212                 AutoClientEnd.message=false;
213         }
214
215         @OnMessage
216         public static void onMessage(String message, Session session) throws IOException {
217                 AutoClientEnd.message = true;
218                 logger.debug("Auto Notification Recieved Message " + message + " Session info is : " + session.getId());
219                 try {
220                         notification = NotificationUnMarshal.notificationJSON(message);
221                 } catch (Exception e) {
222                         logger.error("PE500 " + e);
223                 }
224                 if(AutoClientEnd.session == session){
225                         try{
226                                 NotificationStore.recordNotification(notification);
227                         }catch(Exception e){
228                                 logger.error(e);
229                         }
230                         if(oldNotification!=notification){
231                                 oldNotification= notification;
232                                 callHandler();
233                         }
234                 }else{
235                         session.close();
236                 }
237                 AutoClientEnd.message = false;
238         }
239 }