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