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