Policy TestSuite Enabled
[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.getMessage());
169                                 }
170                         } else if (scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) {
171                                 PDPNotification newNotification = MatchStore.checkMatch(notification);
172                                 if (newNotification.getNotificationType() != null) {
173                                         handler.notificationReceived(newNotification);
174                                 }
175                         }
176                 }
177         }
178
179         // WebSockets Code..
180         @OnOpen
181         public void onOpen(Session session) throws IOException {
182                 // session.getBasicRemote().sendText("Connected to Client with Session: "
183                 // + session.getId());
184                 logger.debug("Auto Notification Session Started... " + session.getId());
185                 if(AutoClientEnd.session == null){
186                         AutoClientEnd.session = session;
187                 }
188         }
189
190         @OnError
191         public void onError(Session session, Throwable e) {
192                 // trying to Restart by self.
193                 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Session Error.. "+ session.getId() + "\n Error is : " + e );
194                 // logger.error("Exception Occured"+e);
195                 stop();
196                 if (url != null) {
197                         client = null;
198                         status = false;
199                         error= true;
200                         start(url);
201                 }
202         }
203
204         @OnClose
205         public void onClose(Session session) {
206                 logger.info("Session ended with "+ session.getId());
207                 if(!stop && !message){
208                         // This Block of code is executed if there is any Network Failure or if the Notification is Down. 
209                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Disconnected from Notification Server");
210                         client = null;
211                         status = false;
212                         AutoClientEnd.session=null;
213                         // Try to connect Back to available PDP.
214                         error = true;
215                         start(url);
216                 }
217                 AutoClientEnd.message=false;
218         }
219
220         @OnMessage
221         public void onMessage(String message, Session session) throws JsonParseException, JsonMappingException, IOException {
222                 AutoClientEnd.message = true;
223                 logger.debug("Auto Notification Recieved Message " + message + " Session info is : " + session.getId());
224                 try {
225                         notification = NotificationUnMarshal.notificationJSON(message);
226                 } catch (Exception e) {
227                         logger.error("PE500 " + e);
228                 }
229                 if(AutoClientEnd.session == session){
230                         try{
231                                 NotificationStore.recordNotification(notification);
232                         }catch(Exception e){
233                                 logger.error(e);
234                         }
235                         if(oldNotification!=notification){
236                                 oldNotification= notification;
237                                 callHandler();
238                         }
239                 }else{
240                         session.close();
241                 }
242                 AutoClientEnd.message = false;
243         }
244 }