Refactor code for nested stmts in policy std
[policy/engine.git] / PolicyEngineAPI / src / main / java / org / onap / policy / std / StdPolicyEngine.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * PolicyEngineAPI
4  * ================================================================================
5  * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  * 
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  * 
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.std;
23
24 import static org.onap.policy.std.utils.PolicyConfigConstants.BAD_REQUEST_STATUS_CODE;
25 import static org.onap.policy.std.utils.PolicyConfigConstants.CLIENT_ID_PROP_NAME;
26 import static org.onap.policy.std.utils.PolicyConfigConstants.CLIENT_KEY_PROP_NAME;
27 import static org.onap.policy.std.utils.PolicyConfigConstants.COMMA;
28 import static org.onap.policy.std.utils.PolicyConfigConstants.CREATE_DICTIONARY_ITEM_RESOURCE_NAME;
29 import static org.onap.policy.std.utils.PolicyConfigConstants.CREATE_POLICY_RESOURCE_NAME;
30 import static org.onap.policy.std.utils.PolicyConfigConstants.DATE_FORMAT;
31 import static org.onap.policy.std.utils.PolicyConfigConstants.DEFAULT_NOTIFICATION;
32 import static org.onap.policy.std.utils.PolicyConfigConstants.DELETE_POLICY_RESOURCE_NAME;
33 import static org.onap.policy.std.utils.PolicyConfigConstants.DMAAP;
34 import static org.onap.policy.std.utils.PolicyConfigConstants.ENVIRONMENT_PROP_NAME;
35 import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_AUTH_GET_PERM;
36 import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_DATA_ISSUE;
37 import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_INVALID_PDPS;
38 import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_WHILE_CONNECTING;
39 import static org.onap.policy.std.utils.PolicyConfigConstants.GET_CONFIG_RESOURCE_NAME;
40 import static org.onap.policy.std.utils.PolicyConfigConstants.GET_DECISION_RESOURCE_NAME;
41 import static org.onap.policy.std.utils.PolicyConfigConstants.GET_DICTIONARY_ITEMS_RESOURCE_NAME;
42 import static org.onap.policy.std.utils.PolicyConfigConstants.GET_METRICS_RESOURCE_NAME;
43 import static org.onap.policy.std.utils.PolicyConfigConstants.HTTP;
44 import static org.onap.policy.std.utils.PolicyConfigConstants.JUNIT_PROP_NAME;
45 import static org.onap.policy.std.utils.PolicyConfigConstants.NOTIFICATION_SERVERS_PROP_NAME;
46 import static org.onap.policy.std.utils.PolicyConfigConstants.NOTIFICATION_TOPIC_PROP_NAME;
47 import static org.onap.policy.std.utils.PolicyConfigConstants.NOTIFICATION_TYPE_PROP_NAME;
48 import static org.onap.policy.std.utils.PolicyConfigConstants.PDP_URL_PROP_NAME;
49 import static org.onap.policy.std.utils.PolicyConfigConstants.PDP_VALUE_REGEX;
50 import static org.onap.policy.std.utils.PolicyConfigConstants.PE300;
51 import static org.onap.policy.std.utils.PolicyConfigConstants.POLICY_ENGINE_IMPORT_RESOURCE_NAME;
52 import static org.onap.policy.std.utils.PolicyConfigConstants.PUSH_POLICY_RESOURCE_NAME;
53 import static org.onap.policy.std.utils.PolicyConfigConstants.REGEX;
54 import static org.onap.policy.std.utils.PolicyConfigConstants.SEMICOLLON;
55 import static org.onap.policy.std.utils.PolicyConfigConstants.SEND_EVENT_RESOURCE_NAME;
56 import static org.onap.policy.std.utils.PolicyConfigConstants.TEST_POLICY_NAME;
57 import static org.onap.policy.std.utils.PolicyConfigConstants.UEB;
58 import static org.onap.policy.std.utils.PolicyConfigConstants.UEB_API_KEY_PROP_NAME;
59 import static org.onap.policy.std.utils.PolicyConfigConstants.UEB_API_SECRET_PROP_NAME;
60 import static org.onap.policy.std.utils.PolicyConfigConstants.UNAUTHORIZED_STATUS_CODE;
61 import static org.onap.policy.std.utils.PolicyConfigConstants.UPDATE_DICTIONARY_ITEM_RESOURCE_NAME;
62 import static org.onap.policy.std.utils.PolicyConfigConstants.UPDATE_POLICY_RESOURCE_NAME;
63 import java.io.BufferedReader;
64 import java.io.IOException;
65 import java.io.StringReader;
66 import java.io.UnsupportedEncodingException;
67 import java.net.URL;
68 import java.net.URLConnection;
69 import java.nio.charset.StandardCharsets;
70 import java.nio.file.Files;
71 import java.nio.file.Path;
72 import java.nio.file.Paths;
73 import java.text.ParseException;
74 import java.text.SimpleDateFormat;
75 import java.util.ArrayList;
76 import java.util.Arrays;
77 import java.util.Base64;
78 import java.util.Collection;
79 import java.util.Collections;
80 import java.util.Date;
81 import java.util.HashMap;
82 import java.util.List;
83 import java.util.Map;
84 import java.util.Properties;
85 import java.util.UUID;
86 import javax.json.Json;
87 import javax.json.JsonObject;
88 import javax.json.JsonReader;
89 import javax.xml.parsers.DocumentBuilder;
90 import javax.xml.parsers.DocumentBuilderFactory;
91 import org.onap.policy.api.AttributeType;
92 import org.onap.policy.api.ConfigRequestParameters;
93 import org.onap.policy.api.DecisionRequestParameters;
94 import org.onap.policy.api.DecisionResponse;
95 import org.onap.policy.api.DeletePolicyParameters;
96 import org.onap.policy.api.DictionaryParameters;
97 import org.onap.policy.api.DictionaryResponse;
98 import org.onap.policy.api.EventRequestParameters;
99 import org.onap.policy.api.ImportParameters;
100 import org.onap.policy.api.MetricsRequestParameters;
101 import org.onap.policy.api.MetricsResponse;
102 import org.onap.policy.api.NotificationHandler;
103 import org.onap.policy.api.NotificationScheme;
104 import org.onap.policy.api.PDPNotification;
105 import org.onap.policy.api.PolicyChangeResponse;
106 import org.onap.policy.api.PolicyClass;
107 import org.onap.policy.api.PolicyConfig;
108 import org.onap.policy.api.PolicyConfigException;
109 import org.onap.policy.api.PolicyConfigType;
110 import org.onap.policy.api.PolicyDecisionException;
111 import org.onap.policy.api.PolicyEngineException;
112 import org.onap.policy.api.PolicyEventException;
113 import org.onap.policy.api.PolicyException;
114 import org.onap.policy.api.PolicyParameters;
115 import org.onap.policy.api.PolicyResponse;
116 import org.onap.policy.api.PolicyType;
117 import org.onap.policy.api.PushPolicyParameters;
118 import org.onap.policy.common.logging.flexlogger.FlexLogger;
119 import org.onap.policy.common.logging.flexlogger.Logger;
120 import org.onap.policy.models.APIDictionaryResponse;
121 import org.onap.policy.models.APIPolicyConfigResponse;
122 import org.onap.policy.std.utils.PolicyCommonConfigConstants;
123 import org.onap.policy.utils.AAFEnvironment;
124 import org.onap.policy.utils.PolicyUtils;
125 import org.onap.policy.xacml.api.XACMLErrorConstants;
126 import org.springframework.core.io.FileSystemResource;
127 import org.springframework.http.HttpEntity;
128 import org.springframework.http.HttpHeaders;
129 import org.springframework.http.HttpMethod;
130 import org.springframework.http.HttpStatus;
131 import org.springframework.http.MediaType;
132 import org.springframework.http.ResponseEntity;
133 import org.springframework.util.LinkedMultiValueMap;
134 import org.springframework.web.client.HttpClientErrorException;
135 import org.springframework.web.client.RestTemplate;
136 import org.xml.sax.InputSource;
137 import com.fasterxml.jackson.core.JsonProcessingException;
138 import com.google.gson.Gson;
139 import com.google.gson.GsonBuilder;
140
141 /**
142  * PolicyEngine Implementation class
143  * 
144  * @version 1.0
145  */
146 public class StdPolicyEngine {
147
148     private static String clientEncoding = null;
149     private String contentType = null;
150     private static List<String> pdps = null;
151     private static String environment = null;
152     private static String userName = null;
153     private static String pass = null;
154     private static List<String> encoding = null;
155     private static boolean junit = false;
156     private List<String> notificationType = new ArrayList<>();
157     private List<String> notificationURLList = new ArrayList<>();
158     private NotificationScheme scheme = null;
159     private NotificationHandler handler = null;
160     private AutoClientUEB uebClientThread = null;
161     private Thread registerUEBThread = null;
162     private boolean uebThread = false;
163     private AutoClientDMAAP dmaapClientThread = null;
164     private Thread registerDMAAPThread = null;
165     private boolean dmaapThread = false;
166     private String topic = null;
167     private String apiKey = null;
168     private String apiSecret = null;
169
170     private static final String UNIQUEID = UUID.randomUUID().toString();
171     private static final Logger LOGGER = FlexLogger.getLogger(StdPolicyConfig.class.getName());
172
173     /*
174      * Taking the Property file even if it null.
175      */
176     public StdPolicyEngine(final String propertyFilePath, final String clientKey) throws PolicyEngineException {
177         setProperty(propertyFilePath, clientKey);
178     }
179     
180     /*
181      * Taking the Property structure even if it null.
182      */
183     public StdPolicyEngine(final Properties properties, final String clientKey) throws PolicyEngineException {
184         setProperty(properties, clientKey);
185     }
186
187     /*
188      * Taking the Notification Constructor.
189      */
190     public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme,
191             final NotificationHandler handler) throws PolicyEngineException {
192         setProperty(propertyFilePath, null);
193         this.scheme = scheme;
194         this.handler = handler;
195         if ((!UEB.equals(notificationType.get(0))) || (!DMAAP.equals(notificationType.get(0)))) {
196             AutoClientEnd.setAuto(scheme, handler);
197         }
198         notification(scheme, handler);
199     }
200
201     /*
202      * Taking the Notification Constructor.
203      */
204     public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme)
205             throws PolicyEngineException {
206         setProperty(propertyFilePath, null);
207         this.scheme = scheme;
208         setScheme(scheme);
209     }
210
211     /*
212      * sendEvent API Implementation
213      */
214     public Collection<PolicyResponse> sendEvent(final Map<String, String> eventAttributes, final UUID requestID)
215             throws PolicyEventException {
216         return sendEventImpl(eventAttributes, requestID);
217     }
218
219     /*
220      * sendEvent API Implementation for eventRequestParameters
221      */
222     public Collection<PolicyResponse> sendEvent(final EventRequestParameters eventRequestParameters)
223             throws PolicyEventException {
224         if (eventRequestParameters == null) {
225             final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. ";
226             LOGGER.error(message);
227             throw new PolicyEventException(message);
228         }
229         return sendEventImpl(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID());
230     }
231
232     /*
233      * getConfig using configRequestParameters Implementation
234      */
235     public Collection<PolicyConfig> getConfig(final ConfigRequestParameters configRequestParameters)
236             throws PolicyConfigException {
237         return getConfigImpl(configRequestParameters);
238     }
239
240     /*
241      * listPolicies using configRequestParameters Implementation
242      */
243     public Collection<String> listConfig(final ConfigRequestParameters listPolicyRequestParameters)
244             throws PolicyConfigException {
245         return listConfigImpl(listPolicyRequestParameters);
246     }
247
248     /*
249      * getDecision using the decision Attributes.
250      */
251     public DecisionResponse getDecision(final String onapName, final Map<String, String> decisionAttributes,
252             final UUID requestID) throws PolicyDecisionException {
253         return getDecisionImpl(onapName, decisionAttributes, requestID);
254     }
255
256     /*
257      * getDecision Using decisionRequestParameters.
258      */
259     public DecisionResponse getDecision(final DecisionRequestParameters decisionRequestParameters)
260             throws PolicyDecisionException {
261         if (decisionRequestParameters == null) {
262             final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. ";
263             LOGGER.error(message);
264             throw new PolicyDecisionException(message);
265         }
266         return getDecisionImpl(decisionRequestParameters.getOnapName(),
267                 decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID());
268     }
269
270     /*
271      * getMetrics using metricsRequestParameters
272      */
273     public MetricsResponse getMetrics(final MetricsRequestParameters parameters) throws PolicyException {
274         return getMetricsImpl(parameters);
275     }
276
277     public MetricsResponse getMetricsImpl(final MetricsRequestParameters parameters) throws PolicyException {
278         String body = null;
279         // Create the Request
280         try {
281             if (parameters != null) {
282                 body = PolicyUtils.objectToJsonString(parameters);
283             }
284         } catch (final JsonProcessingException jsonProcessingException) {
285             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
286             LOGGER.error(message);
287             throw new PolicyException(message, jsonProcessingException);
288         }
289
290         final StdMetricsResponse response = new StdMetricsResponse();
291         // Get Response.
292         try {
293             final ResponseEntity<String> result =
294                     callNewPDP(GET_METRICS_RESOURCE_NAME, HttpMethod.GET, body, String.class);
295             // Process response
296             response.setResponseMessage(result.getBody());
297             response.setResponseCode(result.getStatusCode().value());
298             return response;
299         } catch (final PolicyException exception) {
300             if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
301                 LOGGER.error(exception);
302                 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
303                 response.setResponseCode(ex.getRawStatusCode());
304                 response.setResponseMessage(exception.getMessage());
305                 return response;
306             }
307             final String message =
308                     XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
309             LOGGER.error(message, exception);
310             throw new PolicyException(message, exception);
311         }
312     }
313
314     /*
315      * PushPolicy using pushPolicyParameters.
316      */
317     public PolicyChangeResponse pushPolicy(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
318         return pushPolicyImpl(pushPolicyParameters);
319     }
320
321     public PolicyChangeResponse pushPolicyImpl(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
322         final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
323         String body = null;
324         // Create Request.
325         try {
326             body = PolicyUtils.objectToJsonString(pushPolicyParameters);
327         } catch (final JsonProcessingException e) {
328             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
329             LOGGER.error(message);
330             throw new PolicyException(message, e);
331         }
332         // Get Response.
333         try {
334             final ResponseEntity<String> result =
335                     callNewPDP(PUSH_POLICY_RESOURCE_NAME, HttpMethod.PUT, body, String.class);
336             // Process response
337             response.setResponseMessage(result.getBody());
338             response.setResponseCode(result.getStatusCode().value());
339             return response;
340         } catch (final PolicyException exception) {
341             return processException(exception);
342         }
343     }
344
345     /*
346      * Delete a Policy using deletePolicyParameters
347      */
348     public PolicyChangeResponse deletePolicy(final DeletePolicyParameters parameters) throws PolicyException {
349         return deletePolicyImpl(parameters);
350     }
351
352     private PolicyChangeResponse deletePolicyImpl(final DeletePolicyParameters parameters) throws PolicyException {
353         final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
354         String body = null;
355         // Create Request.
356         try {
357             body = PolicyUtils.objectToJsonString(parameters);
358         } catch (final JsonProcessingException e) {
359             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
360             LOGGER.error(message);
361             throw new PolicyException(message, e);
362         }
363         // Get Response.
364         try {
365             final ResponseEntity<String> result =
366                     callNewPDP(DELETE_POLICY_RESOURCE_NAME, HttpMethod.DELETE, body, String.class);
367             // Process response
368             response.setResponseMessage(result.getBody());
369             response.setResponseCode(result.getStatusCode().value());
370         } catch (final PolicyException exception) {
371             return processException(exception);
372         }
373         return response;
374     }
375
376     /*
377      * getDictionaryItem Using dictionaryParameters
378      */
379     public DictionaryResponse getDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
380         return getDictionaryItemImpl(parameters);
381     }
382
383     private DictionaryResponse getDictionaryItemImpl(final DictionaryParameters parameters) throws PolicyException {
384         final StdDictionaryResponse response = new StdDictionaryResponse();
385         String body = "{}";
386         // Create Request.
387         try {
388             body = PolicyUtils.objectToJsonString(parameters);
389         } catch (final JsonProcessingException e) {
390             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
391             LOGGER.error(message);
392             throw new PolicyException(message, e);
393         }
394         // Get Response.
395         try {
396             final ResponseEntity<APIDictionaryResponse> result =
397                     callNewPDP(GET_DICTIONARY_ITEMS_RESOURCE_NAME, HttpMethod.POST, body, APIDictionaryResponse.class);
398             // Process response
399             return dictionaryResult(result.getBody());
400         } catch (final Exception exception) {
401             if (exception.getCause().getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
402                 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM
403                         + GET_DICTIONARY_ITEMS_RESOURCE_NAME;
404                 LOGGER.error(message);
405                 response.setResponseMessage(message);
406                 response.setResponseCode(HttpStatus.UNAUTHORIZED.value());
407                 return response;
408             }
409             if (exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
410                 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
411                 response.setResponseMessage(message);
412                 response.setResponseCode(HttpStatus.BAD_REQUEST.value());
413                 return response;
414             }
415             final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
416             LOGGER.error(message, exception);
417             response.setResponseMessage(message);
418             response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
419             return response;
420         }
421     }
422
423     @SuppressWarnings("unchecked")
424     private StdDictionaryResponse dictionaryResult(final APIDictionaryResponse body) {
425         final StdDictionaryResponse response = new StdDictionaryResponse();
426         response.setResponseCode(body.getResponseCode());
427         response.setResponseMessage(body.getResponseMessage());
428         response.setDictionaryData((Map<String, String>) body.getDictionaryData());
429         if (body.getDictionaryJson() != null) {
430             final Gson objGson = new GsonBuilder().create();
431             final String mapToJson = objGson.toJson(body.getDictionaryJson());
432             try (final JsonReader jsonReader = Json.createReader(new StringReader(mapToJson));) {
433                 final JsonObject object = jsonReader.readObject();
434                 response.setDictionaryJson(object);
435             }
436         }
437         return response;
438     }
439
440     /*
441      * createDictinaryItem Using dictionaryParameters.
442      */
443     public PolicyChangeResponse createDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
444         return createUpdateDictionaryItemImpl(parameters, false);
445     }
446
447     /*
448      * updateDictinaryItem Using dictionaryParameters.
449      */
450     public PolicyChangeResponse updateDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
451         return createUpdateDictionaryItemImpl(parameters, true);
452     }
453
454     private PolicyChangeResponse createUpdateDictionaryItemImpl(final DictionaryParameters parameters,
455             final boolean updateFlag) throws PolicyException {
456
457         final String resource = getDictionaryResouceName(updateFlag);
458         String body = null;
459         // Create Request.
460         try {
461             body = PolicyUtils.objectToJsonString(parameters);
462         } catch (final JsonProcessingException jsonProcessingException) {
463             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
464             LOGGER.error(message);
465             throw new PolicyException(message, jsonProcessingException);
466         }
467         // Get Response.
468         try {
469             final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
470             final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
471             // Process response
472             response.setResponseMessage(result.getBody());
473             response.setResponseCode(result.getStatusCode().value());
474             return response;
475         } catch (final PolicyException exception) {
476             return processException(exception);
477         }
478     }
479
480     private String getDictionaryResouceName(final boolean updateFlag) {
481         return updateFlag ? UPDATE_DICTIONARY_ITEM_RESOURCE_NAME : CREATE_DICTIONARY_ITEM_RESOURCE_NAME;
482     }
483
484     /*
485      * PolicyEngine Import
486      */
487     public PolicyChangeResponse policyEngineImport(final ImportParameters importParameters) throws PolicyException {
488         return policyEngineImportImpl(importParameters);
489     }
490
491     private PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters) throws PolicyException {
492         final LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
493         // Create Request.
494         try {
495             final String body = PolicyUtils.objectToJsonString(importParameters);
496             parameters.set("importParametersJson", body);
497             parameters.set("file", new FileSystemResource(importParameters.getFilePath()));
498         } catch (final Exception e) {
499             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
500             LOGGER.error(message);
501             throw new PolicyException(message, e);
502         }
503         contentType = MediaType.MULTIPART_FORM_DATA_VALUE;
504         // Get Response.
505         try {
506             final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
507             final ResponseEntity<String> result =
508                     callNewPDP(POLICY_ENGINE_IMPORT_RESOURCE_NAME, HttpMethod.POST, parameters, String.class);
509             // Process response
510             response.setResponseMessage(result.getBody());
511             response.setResponseCode(result.getStatusCode().value());
512             return response;
513         } catch (final PolicyException exception) {
514             return processException(exception);
515         } finally {
516             contentType = null;
517         }
518     }
519
520     /*
521      * createPolicy Using policyParameters.
522      */
523     public PolicyChangeResponse createPolicy(final PolicyParameters policyParameters) throws PolicyException {
524         return createUpdatePolicyImpl(policyParameters, false);
525     }
526
527     /*
528      * updatePolicy using policyParameters.
529      */
530     public PolicyChangeResponse updatePolicy(final PolicyParameters policyParameters) throws PolicyException {
531         return createUpdatePolicyImpl(policyParameters, true);
532     }
533
534     private PolicyChangeResponse createUpdatePolicyImpl(final PolicyParameters policyParameters,
535             final boolean updateFlag) throws PolicyException {
536         final String resource = getPolicyResourceName(updateFlag);
537         String body = null;
538         // Create Request.
539         try {
540             body = PolicyUtils.objectToJsonString(policyParameters);
541         } catch (final JsonProcessingException e) {
542             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
543             LOGGER.error(message);
544             throw new PolicyException(message, e);
545         }
546         // Get Response.
547         try {
548             final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
549             final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
550             // Process response
551             response.setResponseMessage(result.getBody());
552             response.setResponseCode(result.getStatusCode().value());
553             return response;
554         } catch (final PolicyException exception) {
555             return processException(exception);
556         }
557     }
558
559     private String getPolicyResourceName(final boolean updateFlag) {
560         return updateFlag ? UPDATE_POLICY_RESOURCE_NAME : CREATE_POLICY_RESOURCE_NAME;
561     }
562
563     private PolicyChangeResponse processException(final PolicyException exception) throws PolicyException {
564         final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
565         if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
566             LOGGER.error(exception);
567             final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
568             response.setResponseCode(ex.getRawStatusCode());
569             response.setResponseMessage(exception.getMessage());
570             return response;
571         } else {
572             final String message =
573                     XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
574             LOGGER.error(message, exception);
575             throw new PolicyException(message, exception);
576         }
577     }
578
579     private DecisionResponse getDecisionImpl(final String onapName, final Map<String, String> decisionAttributes,
580             final UUID requestID) throws PolicyDecisionException {
581         String body = null;
582         // Create Request.
583         try {
584             final DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters();
585             decisionRequestParameters.setDecisionAttributes(decisionAttributes);
586             decisionRequestParameters.setOnapName(onapName);
587             decisionRequestParameters.setRequestID(requestID);
588             body = PolicyUtils.objectToJsonString(decisionRequestParameters);
589         } catch (final JsonProcessingException e) {
590             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
591             LOGGER.error(message);
592             throw new PolicyDecisionException(message, e);
593         }
594         // Get Response.
595         try {
596             final ResponseEntity<StdDecisionResponse> result =
597                     callNewPDP(GET_DECISION_RESOURCE_NAME, HttpMethod.POST, body, StdDecisionResponse.class);
598             // Process response
599             return result.getBody();
600         } catch (final Exception exception) {
601             final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
602             final String message = getErrorMessage(exception, defaulMessage, GET_DECISION_RESOURCE_NAME);
603             LOGGER.error(message, exception);
604             throw new PolicyDecisionException(message, exception);
605         }
606     }
607
608     private Collection<PolicyConfig> getConfigImpl(final ConfigRequestParameters configRequestParameters)
609             throws PolicyConfigException {
610         String body = null;
611         // Create Request.
612         try {
613             body = PolicyUtils.objectToJsonString(configRequestParameters);
614         } catch (final JsonProcessingException e) {
615             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
616             LOGGER.error(message);
617             throw new PolicyConfigException(message, e);
618         }
619         // Get Response.
620         try {
621             final ResponseEntity<APIPolicyConfigResponse[]> result =
622                     callNewPDP(GET_CONFIG_RESOURCE_NAME, HttpMethod.POST, body, APIPolicyConfigResponse[].class);
623             // Process Response
624             return configResult(result.getBody());
625         } catch (final Exception exception) {
626             final String defaulMessage = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS + pdps;
627             final String message = getErrorMessage(exception, defaulMessage, GET_CONFIG_RESOURCE_NAME);
628             LOGGER.error(message, exception);
629             throw new PolicyConfigException(message, exception);
630         }
631     }
632
633     private ArrayList<PolicyConfig> configResult(final APIPolicyConfigResponse[] response)
634             throws PolicyConfigException {
635         final ArrayList<PolicyConfig> result = new ArrayList<>();
636         if (response == null) {
637             return result;
638         }
639
640         for (final APIPolicyConfigResponse policyConfigResponse : response) {
641             final StdPolicyConfig policyConfig = new StdPolicyConfig();
642             policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage());
643             policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions());
644             policyConfig.setPolicyConfigStatus(policyConfigResponse.getPolicyConfigStatus());
645             policyConfig.setPolicyName(policyConfigResponse.getPolicyName());
646             policyConfig.setPolicyType(policyConfigResponse.getType());
647             policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion());
648             policyConfig.setPolicyType(policyConfigResponse.getPolicyType());
649             policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes());
650             setMatches(policyConfig.getMatchingConditions());
651             if (policyConfigResponse.getType() != null) {
652                 try {
653                     switch (policyConfigResponse.getType()) {
654                         case JSON:
655                             final StringReader reader = new StringReader(policyConfigResponse.getConfig());
656                             try (final JsonReader jsonReader = Json.createReader(reader)) {
657                                 final JsonObject object = jsonReader.readObject();
658                                 policyConfig.setJsonObject(object);
659                             }
660                             break;
661                         case OTHER:
662                             policyConfig.setOther(policyConfigResponse.getConfig());
663                             break;
664                         case PROPERTIES:
665                             final Properties props = new Properties();
666                             props.putAll(policyConfigResponse.getProperty());
667                             policyConfig.setProperties(props);
668                             break;
669                         case XML:
670                             final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
671                             final DocumentBuilder builder = factory.newDocumentBuilder();
672                             final StringReader stringReader = new StringReader(policyConfigResponse.getConfig());
673                             policyConfig.setDocument(builder.parse(new InputSource(stringReader)));
674                             break;
675                     }
676                 } catch (final Exception exception) {
677                     LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + exception);
678                     throw new PolicyConfigException(
679                             XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", exception);
680                 }
681             }
682             result.add(policyConfig);
683         }
684         return result;
685     }
686
687     private void setMatches(final Map<String, String> matchingConditions) {
688         final Matches match = new Matches();
689         final HashMap<String, String> configAttributes = new HashMap<>();
690         try {
691             for (final Map.Entry<String, String> entry : matchingConditions.entrySet()) {
692                 if (PolicyCommonConfigConstants.ONAP_NAME.equalsIgnoreCase(entry.getKey())) {
693                     match.setOnapName(entry.getValue());
694                 } else if (PolicyCommonConfigConstants.CONFIG_NAME.equalsIgnoreCase(entry.getKey())) {
695                     match.setConfigName(entry.getValue());
696                 } else {
697                     configAttributes.put(entry.getKey(), entry.getValue());
698                 }
699             }
700             if (!configAttributes.isEmpty()) {
701                 match.setConfigAttributes(configAttributes);
702             }
703             MatchStore.storeMatch(match);
704         } catch (final Exception e) {
705             LOGGER.error("StoreMatch failed for Onap:" + match.getOnapName() + " Config: " + match.getConfigName(), e);
706         }
707     }
708
709     /*
710      * Generic Rest Client to call PDP services.
711      */
712     <T> ResponseEntity<T> callNewPDP(final String resource, final HttpMethod method, final Object body,
713             final Class<T> responseType) throws PolicyException {
714         final RestTemplate restTemplate = new RestTemplate();
715         final HttpEntity<?> requestEntity = new HttpEntity<>(body, getHeaders());
716         ResponseEntity<T> result = null;
717         HttpClientErrorException exception = null;
718         int pdpsCount = 0;
719         while (pdpsCount < pdps.size()) {
720             try {
721                 result = restTemplate.exchange(pdps.get(0) + "/api/" + resource, method, requestEntity, responseType);
722             } catch (final HttpClientErrorException e) {
723                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
724                 exception = e;
725             } catch (final Exception e) {
726                 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
727                 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
728             }
729             if (result == null) {
730                 Collections.rotate(pdps, -1);
731                 Collections.rotate(encoding, -1);
732                 pdpsCount++;
733             } else {
734                 break;
735             }
736         }
737         if (exception == null || exception.getStatusCode() == null) {
738             return result;
739         }
740
741         final String message = getHttpErrorMessage(exception, resource);
742         LOGGER.error(message);
743         throw new PolicyException(message, exception);
744     }
745
746     private String getHttpErrorMessage(final HttpClientErrorException exception, final String resource) {
747         if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
748             return XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + ERROR_AUTH_GET_PERM
749                     + resource;
750         }
751         if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
752             return XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":"
753                     + exception.getResponseBodyAsString();
754         }
755         if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
756             return XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps + exception;
757         }
758         return XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":"
759                 + exception.getResponseBodyAsString();
760     }
761
762     private HttpHeaders getHeaders() {
763         final HttpHeaders headers = new HttpHeaders();
764         headers.set("ClientAuth", "Basic " + clientEncoding);
765         headers.set("Authorization", "Basic " + encoding.get(0));
766         if (contentType != null) {
767             headers.set("Content-Type", contentType);
768         } else {
769             headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
770         }
771         headers.set("Environment", environment);
772         return headers;
773     }
774
775     private static void setClientEncoding() {
776         final Base64.Encoder encoder = Base64.getEncoder();
777         clientEncoding = encoder.encodeToString((userName + ":" + pass).getBytes(StandardCharsets.UTF_8));
778     }
779
780     private Collection<String> listConfigImpl(final ConfigRequestParameters listRequestParameters)
781             throws PolicyConfigException {
782         final Collection<String> policyList = new ArrayList<>();
783         if (junit) {
784             policyList.add(TEST_POLICY_NAME);
785             return policyList;
786         }
787         final Collection<PolicyConfig> policyConfig = getConfigImpl(listRequestParameters);
788         for (final PolicyConfig policy : policyConfig) {
789             if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains(PE300)) {
790                 policyList.add(policy.getPolicyConfigMessage());
791             } else {
792                 policyList.add("Policy Name: " + policy.getPolicyName());
793             }
794         }
795         return policyList;
796     }
797
798     private Collection<PolicyResponse> sendEventImpl(final Map<String, String> eventAttributes, final UUID requestID)
799             throws PolicyEventException {
800         String body = null;
801         // Create Request.
802         try {
803             // Long way here, can be shortened and will be done.
804             final EventRequestParameters eventRequestParameters = new EventRequestParameters();
805             eventRequestParameters.setEventAttributes(eventAttributes);
806             eventRequestParameters.setRequestID(requestID);
807             body = PolicyUtils.objectToJsonString(eventRequestParameters);
808         } catch (final JsonProcessingException e) {
809             final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
810             LOGGER.error(message);
811             throw new PolicyEventException(message, e);
812         }
813         // Get Response.
814         try {
815             final ResponseEntity<StdPolicyResponse[]> result =
816                     callNewPDP(SEND_EVENT_RESOURCE_NAME, HttpMethod.POST, body, StdPolicyResponse[].class);
817             // Process Response
818             return eventResult(result.getBody());
819         } catch (final Exception exception) {
820             final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
821             final String message = getErrorMessage(exception, defaulMessage, SEND_EVENT_RESOURCE_NAME);
822             LOGGER.error(message, exception);
823             throw new PolicyEventException(message, exception);
824         }
825     }
826
827     private String getErrorMessage(final Exception exception, final String defaulMessage, final String resource) {
828         final Throwable cause = exception.getCause();
829         if (cause != null && cause.getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
830             return XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource;
831         }
832         if (cause != null && exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
833             return XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
834         }
835         return defaulMessage;
836     }
837
838     private ArrayList<PolicyResponse> eventResult(final StdPolicyResponse[] response) {
839         final ArrayList<PolicyResponse> eventResult = new ArrayList<>();
840         if (response != null && response.length > 0) {
841             for (final StdPolicyResponse policyConfigResponse : response) {
842                 eventResult.add(policyConfigResponse);
843             }
844         }
845         return eventResult;
846     }
847
848     private void setProperty(final String propertyFilePath, String clientKey) throws PolicyEngineException {
849         if (propertyFilePath == null) {
850             throw new PolicyEngineException(
851                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided");
852         }
853         final Properties prop = getProperties(propertyFilePath);
854         setProperty(prop,clientKey);
855     }
856     
857     private void setProperty(final Properties properties, String clientKey) throws PolicyEngineException {
858         if (properties == null) {
859             throw new PolicyEngineException(
860                     XACMLErrorConstants.ERROR_DATA_ISSUE + "NO properties provided, the value is NULL");
861         }
862
863         // UEB and DMAAP Settings
864         final String notificationTypeValue = properties.getProperty(NOTIFICATION_TYPE_PROP_NAME);
865         final String serverList = properties.getProperty(NOTIFICATION_SERVERS_PROP_NAME);
866         topic = properties.getProperty(NOTIFICATION_TOPIC_PROP_NAME);
867         apiKey = properties.getProperty(UEB_API_KEY_PROP_NAME);
868         apiSecret = properties.getProperty(UEB_API_SECRET_PROP_NAME);
869
870         setNotificationType(notificationTypeValue);
871
872         if (serverList == null) {
873             notificationType.clear();
874             notificationType.add(DEFAULT_NOTIFICATION);
875             LOGGER.info(
876                     "Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets");
877         } else {
878             notificationURLList = getPropertyValueAsList(serverList.trim());
879         }
880
881         if (topic != null) {
882             topic = topic.trim();
883         } else {
884             LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter.");
885         }
886
887         // Client ID Authorization Settings.
888         final String clientID = properties.getProperty(CLIENT_ID_PROP_NAME);
889         if (clientKey == null) {
890             clientKey = getClientKeyFromProperties(properties);
891         }
892         if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) {
893             LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
894                     + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
895             throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS
896                     + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
897         } else {
898             setClientId(clientID.trim());
899             setClientKey(clientKey.trim());
900         }
901         setEnvironment(properties);
902         // Initializing the values.
903         init();
904         readPdpProperites(properties);
905         // Get JUNIT property from properties file when running tests
906         checkJunit(properties);
907     }
908
909     private void readPdpProperites(final Properties prop) throws PolicyEngineException {
910         // Check the Keys for PDP_URLs
911         for (final String propertyKey : prop.stringPropertyNames()) {
912             if (propertyKey.startsWith(PDP_URL_PROP_NAME)) {
913                 readPDPPropertyURL(prop, propertyKey);
914             }
915         }
916         if (pdps == null || pdps.isEmpty()) {
917             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
918             throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
919         }
920     }
921
922     private void readPDPPropertyURL(Properties prop, String propertyKey) throws PolicyEngineException {
923         final String propertyValue = prop.getProperty(propertyKey);
924         if (propertyValue == null) {
925             throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
926                     + "Properties file doesn't have the PDP_URL parameter");
927         }
928         if (propertyValue.contains(SEMICOLLON)) {
929             final List<String> pdpDefault = Arrays.asList(propertyValue.split(REGEX));
930             for (final String pdpVal : pdpDefault) {
931                 readPDPParam(pdpVal);
932             }
933         } else {
934             readPDPParam(propertyValue);
935         }
936     }
937
938     private void setNotificationType(final String propertyValue) {
939         if (propertyValue == null) {
940             notificationType.add(DEFAULT_NOTIFICATION);
941             LOGGER.info(
942                     "Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets");
943         } else {
944             notificationType = getPropertyValueAsList(propertyValue.trim());
945         }
946     }
947
948     private String getClientKeyFromProperties(final Properties prop) {
949         final String clientKeyValue = prop.getProperty(CLIENT_KEY_PROP_NAME);
950         try {
951             return PolicyUtils.decode(clientKeyValue);
952         } catch (UnsupportedEncodingException | IllegalArgumentException e) {
953             LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
954                     + " Cannot Decode the given Password Proceeding with given Password!!", e);
955         }
956         return clientKeyValue;
957     }
958
959     private Properties getProperties(final String propertyFilePath) throws PolicyEngineException {
960         // Adding logic for remote Properties file.
961         if (propertyFilePath.startsWith(HTTP)) {
962             return getRemoteProperties(propertyFilePath);
963         }
964         return getFileProperties(propertyFilePath);
965     }
966
967     private Properties getFileProperties(final String propertyFilePath) throws PolicyEngineException {
968         final Path file = Paths.get(propertyFilePath);
969         if (!file.toFile().exists()) {
970             throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
971                     + "File doesn't exist in the specified Path " + file.toString());
972         }
973         if (file.toString().endsWith(".properties")) {
974             try (BufferedReader bufferedReader = Files.newBufferedReader(file);) {
975                 final Properties prop = new Properties();
976                 prop.load(bufferedReader);
977                 return prop;
978             } catch (final IOException exception) {
979                 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + exception);
980                 throw new PolicyEngineException(
981                         XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", exception);
982             }
983         }
984         LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath);
985         throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file");
986     }
987
988     private Properties getRemoteProperties(final String propertyFilePath) throws PolicyEngineException {
989         try {
990             final URL configURL = new URL(propertyFilePath);
991             final URLConnection connection = configURL.openConnection();
992             final Properties prop = new Properties();
993             prop.load(connection.getInputStream());
994             return prop;
995         } catch (final IOException e) {
996             LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
997             throw new PolicyEngineException(
998                     XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage());
999         }
1000     }
1001
1002     private List<String> getPropertyValueAsList(final String propertyValue) {
1003         if (propertyValue.contains(COMMA)) {
1004             return Arrays.asList(propertyValue.split(COMMA));
1005         }
1006         final List<String> valuesList = new ArrayList<>();
1007         valuesList.add(propertyValue);
1008         return valuesList;
1009     }
1010
1011     private static void checkJunit(final Properties prop) {
1012         final String junitFlag = prop.getProperty(JUNIT_PROP_NAME);
1013         if (junitFlag == null || junitFlag.isEmpty()) {
1014             LOGGER.info("No JUNIT property provided, this will not be executed as a test.");
1015         } else {
1016             if ("test".equalsIgnoreCase(junitFlag)) {
1017                 StdPolicyEngine.junit = true;
1018             } else {
1019                 StdPolicyEngine.junit = false;
1020             }
1021         }
1022     }
1023
1024     private static void init() {
1025         pdps = new ArrayList<>();
1026         encoding = new ArrayList<>();
1027     }
1028
1029     private static void setEnvironment(final Properties prop) {
1030         environment = prop.getProperty(ENVIRONMENT_PROP_NAME, AAFEnvironment.DEVL.toString());
1031         if (environment.equalsIgnoreCase(AAFEnvironment.TEST.toString())) {
1032             environment = AAFEnvironment.TEST.toString();
1033         } else if (environment.equalsIgnoreCase(AAFEnvironment.PROD.toString())) {
1034             environment = AAFEnvironment.PROD.toString();
1035         } else {
1036             environment = AAFEnvironment.DEVL.toString();
1037         }
1038     }
1039
1040     private static void setClientId(final String clientID) {
1041         userName = clientID;
1042     }
1043
1044     /*
1045      * Read the PDP_URL parameter
1046      */
1047     private void readPDPParam(final String pdpVal) throws PolicyEngineException {
1048         if (pdpVal.contains(COMMA)) {
1049             final List<String> pdpValues = Arrays.asList(pdpVal.split(PDP_VALUE_REGEX));
1050             if (pdpValues.size() == 3) {
1051                 // 0 - PDPURL
1052                 pdps.add(pdpValues.get(0));
1053                 // 1:2 will be UserID:Password
1054                 final String userID = pdpValues.get(1);
1055                 final String userPas = pdpValues.get(2);
1056                 final Base64.Encoder encoder = Base64.getEncoder();
1057                 encoding.add(encoder.encodeToString((userID + ":" + userPas).getBytes(StandardCharsets.UTF_8)));
1058             } else {
1059                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues);
1060                 throw new PolicyEngineException(
1061                         XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues);
1062             }
1063         } else {
1064             LOGGER.error(
1065                     XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal);
1066             throw new PolicyEngineException(
1067                     XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values.");
1068         }
1069     }
1070
1071     /*
1072      * Allowing changes to the scheme and Handler.
1073      */
1074     public void notification(final NotificationScheme scheme, final NotificationHandler handler) {
1075         this.scheme = scheme;
1076         this.handler = handler;
1077         LOGGER.debug("Scheme is : " + scheme.toString());
1078         LOGGER.debug("Handler is : " + handler.getClass().getName());
1079
1080         if (UEB.equals(notificationType.get(0))) {
1081             if (this.uebThread) {
1082                 AutoClientUEB.setAuto(scheme, handler);
1083                 this.uebThread = registerUEBThread.isAlive();
1084             }
1085         } else if (notificationType.get(0).equals(DMAAP)) {
1086             if (this.dmaapThread) {
1087                 AutoClientDMAAP.setAuto(scheme, handler);
1088                 this.dmaapThread = registerDMAAPThread.isAlive();
1089             }
1090         } else {
1091             AutoClientEnd.setAuto(scheme, handler);
1092         }
1093
1094         if (junit) {
1095             return;
1096         }
1097         if (pdps == null) {
1098             return;
1099         }
1100
1101         if (UEB.equals(notificationType.get(0)) && !this.uebThread) {
1102             this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret);
1103             AutoClientUEB.setAuto(scheme, handler);
1104             this.registerUEBThread = new Thread(this.uebClientThread);
1105             this.registerUEBThread.start();
1106             this.uebThread = true;
1107         } else if (notificationType.get(0).equals(DMAAP) && !this.dmaapThread) {
1108             this.dmaapClientThread = new AutoClientDMAAP(notificationURLList, topic, userName, pass);
1109             AutoClientDMAAP.setAuto(scheme, handler);
1110             this.registerDMAAPThread = new Thread(this.dmaapClientThread);
1111             this.registerDMAAPThread.start();
1112             this.dmaapThread = true;
1113         } else {
1114             if (pdps.get(0) != null) {
1115                 if (AutoClientEnd.getUrl() == null) {
1116                     AutoClientEnd.start(pdps.get(0));
1117                 } else {
1118                     AutoClientEnd.stop();
1119                     AutoClientEnd.start(pdps.get(0));
1120                 }
1121             }
1122         }
1123     }
1124
1125     /*
1126      * Gets the Notification if one exists. Used only for Manual Polling purposes.
1127      */
1128     public PDPNotification getNotification() {
1129         // Check if there is proper scheme..
1130         PDPNotification notification;
1131         if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)
1132                 || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
1133             if (UEB.equals(notificationType.get(0))) {
1134                 ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID);
1135                 notification = ManualClientEndUEB.result(scheme);
1136             } else if (notificationType.get(0).equals(DMAAP)) {
1137                 ManualClientEndDMAAP.start(notificationURLList, topic, UNIQUEID, userName, pass);
1138                 notification = ManualClientEndDMAAP.result(scheme);
1139             } else {
1140                 ManualClientEnd.start(pdps.get(0));
1141                 LOGGER.debug("manual notification requested.. : " + scheme.toString());
1142                 notification = ManualClientEnd.result(scheme);
1143             }
1144             if (notification == null) {
1145                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet..");
1146                 return null;
1147             }
1148             return notification;
1149         }
1150         return null;
1151     }
1152
1153     /*
1154      * Setting the Scheme.
1155      */
1156     public void setScheme(final NotificationScheme scheme) {
1157         this.scheme = scheme;
1158         if (UEB.equals(notificationType.get(0))) {
1159             AutoClientUEB.setScheme(this.scheme);
1160             if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1161                 ManualClientEndUEB.createTopic(pdps.get(0), UNIQUEID, notificationURLList);
1162             }
1163         } else if (notificationType.get(0).equals(DMAAP)) {
1164             AutoClientDMAAP.setScheme(this.scheme);
1165             if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1166                 ManualClientEndDMAAP.createTopic(topic, UNIQUEID, notificationURLList, userName, pass);
1167             }
1168         } else {
1169             AutoClientEnd.setScheme(this.scheme);
1170         }
1171     }
1172
1173     /*
1174      * Returns the Scheme
1175      */
1176     public NotificationScheme getScheme() {
1177         return this.scheme;
1178     }
1179
1180     /*
1181      * Returns the NotificationHandler
1182      */
1183     public NotificationHandler getNotificationHandler() {
1184         return this.handler;
1185     }
1186
1187     /*
1188      * Stop the Notification Service if its running.
1189      */
1190     public void stopNotification() {
1191         if (this.scheme != null && this.handler != null
1192                 && (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)
1193                         || this.scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS))) {
1194             LOGGER.info("Clear Notification called.. ");
1195             if (UEB.equals(notificationType.get(0))) {
1196                 this.uebClientThread.terminate();
1197                 this.uebThread = false;
1198             } else if (notificationType.get(0).equals(DMAAP)) {
1199                 this.dmaapClientThread.terminate();
1200                 this.dmaapThread = false;
1201             } else {
1202                 AutoClientEnd.stop();
1203             }
1204         }
1205     }
1206
1207     /*
1208      * Push a policy to the PDP API implementation
1209      */
1210     public String pushPolicy(final String policyScope, final String policyName, final String policyType,
1211             final String pdpGroup, final UUID requestID) throws PolicyException {
1212         validateParameters(policyName, policyScope);
1213
1214         final PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
1215         pushPolicyParameters.setPolicyName(policyScope + "." + policyName);
1216         pushPolicyParameters.setPolicyType(policyType);
1217         pushPolicyParameters.setPdpGroup(pdpGroup);
1218         pushPolicyParameters.setRequestID(requestID);
1219         return pushPolicyImpl(pushPolicyParameters).getResponseMessage();
1220     }
1221
1222     private boolean isNotValid(final String value) {
1223         return value == null || value.trim().isEmpty();
1224     }
1225
1226     public String createUpdateConfigPolicy(final String policyName, final String policyDescription,
1227             final String onapName, final String configName, final Map<String, String> configAttributes,
1228             final String configType, final String body, final String policyScope, final UUID requestID,
1229             final String riskLevel, final String riskType, final String guard, final String ttlDate,
1230             final boolean updateFlag) throws PolicyException {
1231         return createUpdateConfigPolicyImpl(policyName, policyDescription, onapName, configName, configAttributes,
1232                 configType, body, policyScope, requestID, riskLevel, riskType, guard, ttlDate, updateFlag);
1233     }
1234
1235     /*
1236      * Create Config Policy API Implementation
1237      */
1238     private String createUpdateConfigPolicyImpl(final String policyName, final String policyDescription,
1239             final String onapName, final String configName, final Map<String, String> configAttributes,
1240             final String configType, final String body, final String policyScope, final UUID requestID,
1241             final String riskLevel, final String riskType, final String guard, final String ttlDate,
1242             final boolean updateFlag) throws PolicyException {
1243
1244         validateParameters(policyName, policyScope);
1245
1246         final PolicyParameters policyParameters = new PolicyParameters();
1247         policyParameters.setPolicyClass(PolicyClass.Config);
1248         policyParameters.setPolicyConfigType(PolicyConfigType.Base);
1249         policyParameters.setPolicyName(policyScope + "." + policyName);
1250         policyParameters.setPolicyDescription(policyDescription);
1251         policyParameters.setOnapName(onapName);
1252         policyParameters.setConfigName(configName);
1253
1254         final Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
1255         attributes.put(AttributeType.MATCHING, configAttributes);
1256
1257         policyParameters.setAttributes(attributes);
1258         policyParameters.setConfigBodyType(PolicyType.valueOf(configType));
1259         policyParameters.setConfigBody(body);
1260         policyParameters.setRequestID(requestID);
1261         policyParameters.setRiskLevel(riskLevel);
1262         policyParameters.setRiskType(riskType);
1263         policyParameters.setGuard(Boolean.parseBoolean(guard));
1264         policyParameters.setTtlDate(toDate(ttlDate));
1265         return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1266     }
1267
1268     private Date toDate(final String dateString) {
1269         try {
1270             return new SimpleDateFormat(DATE_FORMAT).parse(dateString);
1271         } catch (final ParseException e) {
1272             LOGGER.warn("Error Parsing date given " + dateString);
1273         }
1274         return null;
1275     }
1276
1277     public String createUpdateConfigFirewallPolicy(final String policyName, final JsonObject firewallJson,
1278             final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1279             final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1280         return createUpdateConfigFirewallPolicyImpl(policyName, firewallJson, policyScope, requestID, riskLevel,
1281                 riskType, guard, ttlDate, updateFlag);
1282     }
1283
1284     /*
1285      * Create Update Config Firewall Policy API implementation
1286      */
1287     private String createUpdateConfigFirewallPolicyImpl(final String policyName, final JsonObject firewallJson,
1288             final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1289             final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1290         validateParameters(policyName, policyScope);
1291
1292         final PolicyParameters policyParameters = new PolicyParameters();
1293         policyParameters.setPolicyClass(PolicyClass.Config);
1294         policyParameters.setPolicyConfigType(PolicyConfigType.Firewall);
1295         policyParameters.setPolicyName(policyScope + "." + policyName);
1296         policyParameters.setConfigBody(firewallJson.toString());
1297         policyParameters.setRequestID(requestID);
1298         policyParameters.setRiskLevel(riskLevel);
1299         policyParameters.setRiskType(riskType);
1300         policyParameters.setGuard(Boolean.parseBoolean(guard));
1301         policyParameters.setTtlDate(toDate(ttlDate));
1302         return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1303     }
1304
1305     private void validateParameters(final String policyName, final String policyScope) throws PolicyException {
1306         if (isNotValid(policyScope)) {
1307             final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
1308             LOGGER.error(message);
1309             throw new PolicyException(message);
1310         }
1311         if (isNotValid(policyName)) {
1312             final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
1313             LOGGER.error(message);
1314             throw new PolicyException(message);
1315         }
1316     }
1317
1318     public static void setClientKey(final String clientKey) {
1319         if (clientKey != null && !clientKey.isEmpty()) {
1320             StdPolicyEngine.pass = clientKey;
1321             setClientEncoding();
1322         }
1323     }
1324
1325     /*
1326      * Get the Environment.
1327      */
1328     public static String getEnvironment() {
1329         return environment;
1330     }
1331
1332     /*
1333      * Rotate the PDP list upon WEBsocket Failures
1334      */
1335     public static void rotatePDPList() {
1336         Collections.rotate(pdps, -1);
1337         Collections.rotate(encoding, -1);
1338     }
1339
1340     /*
1341      * Get the latest PDP
1342      */
1343     public static String getPDPURL() {
1344         return pdps.get(0);
1345     }
1346
1347     // Added for test
1348     String getTopic() {
1349         return topic;
1350     }
1351
1352     // Added for test
1353     List<String> getNotificationType() {
1354         return notificationType;
1355     }
1356
1357     // Added for test
1358     List<String> getNotificationURLList() {
1359         return notificationURLList;
1360     }
1361
1362 }