6a1c586502021693b6f4ca5f41a4fb8baa09edb3
[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 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                 
80                 if (scheme == null || handler == null ||
81                         ! (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS) ||
82                                         scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS) ) ||
83                         AutoClientEnd.client != null) {
84                         return;
85                 }
86                 
87                 // Stop and Start needs to be done.
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&&oldNotification!=notification){
103                                     oldNotification= notification;
104                                     AutoClientEnd.notification = notification;
105                                     callHandler();
106                                 }
107                                 error = false;
108                         }
109                         //
110                 } catch (DeploymentException | IOException | URISyntaxException e) {
111                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
112                         client = null;
113                         status = false;
114                         changeURL();
115                 }
116         }
117         
118         private static void changeURL(){
119                 // Change the PDP if it is not Up. 
120                 StdPolicyEngine.rotatePDPList();
121                 start(StdPolicyEngine.getPDPURL());
122         }
123
124         public static void stop() {
125                 if (client == null) {
126                         return;
127                 }
128                 client.shutdown();
129                 if(session!=null){
130                         try {
131                                 stop = true;
132                                 logger.info("\n Closing Auto Notification WebSocket Connection.. ");
133                                 session.close();
134                                 session = null;
135                         } catch (IOException e) {
136                                 logger.error("Error closing websocket connection", e);
137                         }
138                 }
139                 client = null;
140                 status = false;
141                 stop = false;
142         }
143
144         private static void callHandler() {
145                 if (handler == null || scheme == null) {
146                         return;
147                 }
148                 if (scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)) {
149                         boolean removed = false;
150                         boolean updated = false;
151                         if (notification.getRemovedPolicies() != null && !notification.getRemovedPolicies().isEmpty()) {
152                                 removed = true;
153                         }
154                         if (notification.getLoadedPolicies() != null && !notification.getLoadedPolicies().isEmpty()) {
155                                 updated = true;
156                         }
157                         if (removed && updated) {
158                                 notification.setNotificationType(NotificationType.BOTH);
159                         } else if (removed) {
160                                 notification.setNotificationType(NotificationType.REMOVE);
161                         } else if (updated) {
162                                 notification.setNotificationType(NotificationType.UPDATE);
163                         }
164                         try{
165                                 handler.notificationReceived(notification);
166                         }catch (Exception e){
167                                 logger.error("Error in Clients Handler Object : ", e);
168                         }
169                 } else if (scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS)) {
170                         PDPNotification newNotification = MatchStore.checkMatch(notification);
171                         if (newNotification.getNotificationType() != null) {
172                                 try{
173                                         handler.notificationReceived(newNotification);
174                                 }catch (Exception e){
175                                         logger.error("Error in Clients Handler Object : ", e);
176                                 }
177                         }
178                 }
179         }
180
181         // WebSockets Code..
182         @OnOpen
183         public static void onOpen(Session session){
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 static 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                 stop();
195                 if (url != null) {
196                         client = null;
197                         status = false;
198                         error= true;
199                         start(url);
200                 }
201         }
202
203         @OnClose
204         public static void onClose(Session session) {
205                 logger.info("Session ended with "+ session.getId());
206                 if(!stop && !message){
207                         // This Block of code is executed if there is any Network Failure or if the Notification is Down. 
208                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Disconnected from Notification Server");
209                         client = null;
210                         status = false;
211                         AutoClientEnd.session=null;
212                         // Try to connect Back to available PDP.
213                         error = true;
214                         start(url);
215                 }
216                 AutoClientEnd.message=false;
217         }
218
219         @OnMessage
220         public static void onMessage(String message, Session session) throws IOException {
221                 AutoClientEnd.message = true;
222                 logger.debug("Auto Notification Recieved Message " + message + " Session info is : " + session.getId());
223                 try {
224                         notification = NotificationUnMarshal.notificationJSON(message);
225                 } catch (Exception e) {
226                         logger.error("PE500 " + e);
227                 }
228                 if(AutoClientEnd.session == session){
229                         try{
230                                 NotificationStore.recordNotification(notification);
231                         }catch(Exception e){
232                                 logger.error(e);
233                         }
234                         if(oldNotification!=notification){
235                                 oldNotification= notification;
236                                 callHandler();
237                         }
238                 }else{
239                         session.close();
240                 }
241                 AutoClientEnd.message = false;
242         }
243 }