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