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