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