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