2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.std;
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;
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;
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;
141 * PolicyEngine Implementation class
145 public class StdPolicyEngine {
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;
169 private static final String UNIQUEID = UUID.randomUUID().toString();
170 private static final Logger LOGGER = FlexLogger.getLogger(StdPolicyConfig.class.getName());
173 * Taking the Property file even if it null.
175 public StdPolicyEngine(final String propertyFilePath, final String clientKey) throws PolicyEngineException {
176 setProperty(propertyFilePath, clientKey);
180 * Taking the Notification Constructor.
182 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme,
183 final NotificationHandler handler) throws PolicyEngineException {
184 setProperty(propertyFilePath, null);
185 this.scheme = scheme;
186 this.handler = handler;
187 if ((!UEB.equals(notificationType.get(0))) || (!DMAAP.equals(notificationType.get(0)))) {
188 AutoClientEnd.setAuto(scheme, handler);
190 notification(scheme, handler);
194 * Taking the Notification Constructor.
196 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme)
197 throws PolicyEngineException {
198 setProperty(propertyFilePath, null);
199 this.scheme = scheme;
204 * sendEvent API Implementation
206 public Collection<PolicyResponse> sendEvent(final Map<String, String> eventAttributes, final UUID requestID)
207 throws PolicyEventException {
208 return sendEventImpl(eventAttributes, requestID);
212 * sendEvent API Implementation for eventRequestParameters
214 public Collection<PolicyResponse> sendEvent(final EventRequestParameters eventRequestParameters)
215 throws PolicyEventException {
216 if (eventRequestParameters == null) {
217 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. ";
218 LOGGER.error(message);
219 throw new PolicyEventException(message);
221 return sendEventImpl(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID());
225 * getConfig using configRequestParameters Implementation
227 public Collection<PolicyConfig> getConfig(final ConfigRequestParameters configRequestParameters)
228 throws PolicyConfigException {
229 return getConfigImpl(configRequestParameters);
233 * listPolicies using configRequestParameters Implementation
235 public Collection<String> listConfig(final ConfigRequestParameters listPolicyRequestParameters)
236 throws PolicyConfigException {
237 return listConfigImpl(listPolicyRequestParameters);
241 * getDecision using the decision Attributes.
243 public DecisionResponse getDecision(final String onapName, final Map<String, String> decisionAttributes,
244 final UUID requestID) throws PolicyDecisionException {
245 return getDecisionImpl(onapName, decisionAttributes, requestID);
249 * getDecision Using decisionRequestParameters.
251 public DecisionResponse getDecision(final DecisionRequestParameters decisionRequestParameters)
252 throws PolicyDecisionException {
253 if (decisionRequestParameters == null) {
254 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. ";
255 LOGGER.error(message);
256 throw new PolicyDecisionException(message);
258 return getDecisionImpl(decisionRequestParameters.getOnapName(),
259 decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID());
263 * getMetrics using metricsRequestParameters
265 public MetricsResponse getMetrics(final MetricsRequestParameters parameters) throws PolicyException {
266 return getMetricsImpl(parameters);
269 public MetricsResponse getMetricsImpl(final MetricsRequestParameters parameters) throws PolicyException {
271 // Create the Request
273 if (parameters != null) {
274 body = PolicyUtils.objectToJsonString(parameters);
276 } catch (final JsonProcessingException jsonProcessingException) {
277 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
278 LOGGER.error(message);
279 throw new PolicyException(message, jsonProcessingException);
282 final StdMetricsResponse response = new StdMetricsResponse();
285 final ResponseEntity<String> result =
286 callNewPDP(GET_METRICS_RESOURCE_NAME, HttpMethod.GET, body, String.class);
288 response.setResponseMessage(result.getBody());
289 response.setResponseCode(result.getStatusCode().value());
291 } catch (final PolicyException exception) {
292 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
293 LOGGER.error(exception);
294 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
295 response.setResponseCode(ex.getRawStatusCode());
296 response.setResponseMessage(exception.getMessage());
299 final String message =
300 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
301 LOGGER.error(message, exception);
302 throw new PolicyException(message, exception);
307 * PushPolicy using pushPolicyParameters.
309 public PolicyChangeResponse pushPolicy(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
310 return pushPolicyImpl(pushPolicyParameters);
313 public PolicyChangeResponse pushPolicyImpl(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
314 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
318 body = PolicyUtils.objectToJsonString(pushPolicyParameters);
319 } catch (final JsonProcessingException e) {
320 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
321 LOGGER.error(message);
322 throw new PolicyException(message, e);
326 final ResponseEntity<String> result =
327 callNewPDP(PUSH_POLICY_RESOURCE_NAME, HttpMethod.PUT, body, String.class);
329 response.setResponseMessage(result.getBody());
330 response.setResponseCode(result.getStatusCode().value());
332 } catch (final PolicyException exception) {
333 return processException(exception);
338 * Delete a Policy using deletePolicyParameters
340 public PolicyChangeResponse deletePolicy(final DeletePolicyParameters parameters) throws PolicyException {
341 return deletePolicyImpl(parameters);
344 public PolicyChangeResponse deletePolicyImpl(final DeletePolicyParameters parameters) throws PolicyException {
345 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
349 body = PolicyUtils.objectToJsonString(parameters);
350 } catch (final JsonProcessingException e) {
351 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
352 LOGGER.error(message);
353 throw new PolicyException(message, e);
357 final ResponseEntity<String> result =
358 callNewPDP(DELETE_POLICY_RESOURCE_NAME, HttpMethod.DELETE, body, String.class);
360 response.setResponseMessage(result.getBody());
361 response.setResponseCode(result.getStatusCode().value());
362 } catch (final PolicyException exception) {
363 return processException(exception);
369 * getDictionaryItem Using dictionaryParameters
371 public DictionaryResponse getDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
372 return getDictionaryItemImpl(parameters);
375 public DictionaryResponse getDictionaryItemImpl(final DictionaryParameters parameters) throws PolicyException {
376 final StdDictionaryResponse response = new StdDictionaryResponse();
380 body = PolicyUtils.objectToJsonString(parameters);
381 } catch (final JsonProcessingException e) {
382 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
383 LOGGER.error(message);
384 throw new PolicyException(message, e);
388 final ResponseEntity<APIDictionaryResponse> result =
389 callNewPDP(GET_DICTIONARY_ITEMS_RESOURCE_NAME, HttpMethod.POST, body, APIDictionaryResponse.class);
391 return dictionaryResult(result.getBody());
392 } catch (final Exception exception) {
393 if (exception.getCause().getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
394 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM
395 + GET_DICTIONARY_ITEMS_RESOURCE_NAME;
396 LOGGER.error(message);
397 response.setResponseMessage(message);
398 response.setResponseCode(HttpStatus.UNAUTHORIZED.value());
401 if (exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
402 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
403 response.setResponseMessage(message);
404 response.setResponseCode(HttpStatus.BAD_REQUEST.value());
407 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
408 LOGGER.error(message, exception);
409 response.setResponseMessage(message);
410 response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
415 @SuppressWarnings("unchecked")
416 private StdDictionaryResponse dictionaryResult(final APIDictionaryResponse body) {
417 final StdDictionaryResponse response = new StdDictionaryResponse();
418 response.setResponseCode(body.getResponseCode());
419 response.setResponseMessage(body.getResponseMessage());
420 response.setDictionaryData((Map<String, String>) body.getDictionaryData());
421 if (body.getDictionaryJson() != null) {
422 final Gson objGson = new GsonBuilder().create();
423 final String mapToJson = objGson.toJson(body.getDictionaryJson());
424 try (final JsonReader jsonReader = Json.createReader(new StringReader(mapToJson));) {
425 final JsonObject object = jsonReader.readObject();
426 response.setDictionaryJson(object);
433 * createDictinaryItem Using dictionaryParameters.
435 public PolicyChangeResponse createDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
436 return createUpdateDictionaryItemImpl(parameters, false);
440 * updateDictinaryItem Using dictionaryParameters.
442 public PolicyChangeResponse updateDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
443 return createUpdateDictionaryItemImpl(parameters, true);
446 public PolicyChangeResponse createUpdateDictionaryItemImpl(final DictionaryParameters parameters,
447 final boolean updateFlag) throws PolicyException {
449 final String resource = getDictionaryResouceName(updateFlag);
453 body = PolicyUtils.objectToJsonString(parameters);
454 } catch (final JsonProcessingException jsonProcessingException) {
455 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
456 LOGGER.error(message);
457 throw new PolicyException(message, jsonProcessingException);
461 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
462 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
464 response.setResponseMessage(result.getBody());
465 response.setResponseCode(result.getStatusCode().value());
467 } catch (final PolicyException exception) {
468 return processException(exception);
472 private String getDictionaryResouceName(final boolean updateFlag) {
473 return updateFlag ? UPDATE_DICTIONARY_ITEM_RESOURCE_NAME : CREATE_DICTIONARY_ITEM_RESOURCE_NAME;
477 * PolicyEngine Import
479 public PolicyChangeResponse policyEngineImport(final ImportParameters importParameters) throws PolicyException {
480 return policyEngineImportImpl(importParameters);
483 public PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters) throws PolicyException {
484 final LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
487 final String body = PolicyUtils.objectToJsonString(importParameters);
488 parameters.set("importParametersJson", body);
489 parameters.set("file", new FileSystemResource(importParameters.getFilePath()));
490 } catch (final Exception e) {
491 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
492 LOGGER.error(message);
493 throw new PolicyException(message, e);
495 contentType = MediaType.MULTIPART_FORM_DATA_VALUE;
498 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
499 final ResponseEntity<String> result =
500 callNewPDP(POLICY_ENGINE_IMPORT_RESOURCE_NAME, HttpMethod.POST, parameters, String.class);
502 response.setResponseMessage(result.getBody());
503 response.setResponseCode(result.getStatusCode().value());
505 } catch (final PolicyException exception) {
506 return processException(exception);
513 * createPolicy Using policyParameters.
515 public PolicyChangeResponse createPolicy(final PolicyParameters policyParameters) throws PolicyException {
516 return createUpdatePolicyImpl(policyParameters, false);
520 * updatePolicy using policyParameters.
522 public PolicyChangeResponse updatePolicy(final PolicyParameters policyParameters) throws PolicyException {
523 return createUpdatePolicyImpl(policyParameters, true);
526 public PolicyChangeResponse createUpdatePolicyImpl(final PolicyParameters policyParameters,
527 final boolean updateFlag) throws PolicyException {
528 final String resource = getPolicyResourceName(updateFlag);
532 body = PolicyUtils.objectToJsonString(policyParameters);
533 } catch (final JsonProcessingException e) {
534 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
535 LOGGER.error(message);
536 throw new PolicyException(message, e);
540 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
541 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
543 response.setResponseMessage(result.getBody());
544 response.setResponseCode(result.getStatusCode().value());
546 } catch (final PolicyException exception) {
547 return processException(exception);
551 private String getPolicyResourceName(final boolean updateFlag) {
552 return updateFlag ? UPDATE_POLICY_RESOURCE_NAME : CREATE_POLICY_RESOURCE_NAME;
555 private PolicyChangeResponse processException(final PolicyException exception) throws PolicyException {
556 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
557 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
558 LOGGER.error(exception);
559 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
560 response.setResponseCode(ex.getRawStatusCode());
561 response.setResponseMessage(exception.getMessage());
564 final String message =
565 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
566 LOGGER.error(message, exception);
567 throw new PolicyException(message, exception);
571 public DecisionResponse getDecisionImpl(final String onapName, final Map<String, String> decisionAttributes,
572 final UUID requestID) throws PolicyDecisionException {
576 final DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters();
577 decisionRequestParameters.setDecisionAttributes(decisionAttributes);
578 decisionRequestParameters.setOnapName(onapName);
579 decisionRequestParameters.setRequestID(requestID);
580 body = PolicyUtils.objectToJsonString(decisionRequestParameters);
581 } catch (final JsonProcessingException e) {
582 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
583 LOGGER.error(message);
584 throw new PolicyDecisionException(message, e);
588 final ResponseEntity<StdDecisionResponse> result =
589 callNewPDP(GET_DECISION_RESOURCE_NAME, HttpMethod.POST, body, StdDecisionResponse.class);
591 return result.getBody();
592 } catch (final Exception exception) {
593 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
594 final String message = getErrorMessage(exception, defaulMessage, GET_DECISION_RESOURCE_NAME);
595 LOGGER.error(message, exception);
596 throw new PolicyDecisionException(message, exception);
600 public Collection<PolicyConfig> getConfigImpl(final ConfigRequestParameters configRequestParameters)
601 throws PolicyConfigException {
605 body = PolicyUtils.objectToJsonString(configRequestParameters);
606 } catch (final JsonProcessingException e) {
607 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
608 LOGGER.error(message);
609 throw new PolicyConfigException(message, e);
613 final ResponseEntity<APIPolicyConfigResponse[]> result =
614 callNewPDP(GET_CONFIG_RESOURCE_NAME, HttpMethod.POST, body, APIPolicyConfigResponse[].class);
616 return configResult(result.getBody());
617 } catch (final Exception exception) {
618 final String defaulMessage = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS + pdps;
619 final String message = getErrorMessage(exception, defaulMessage, GET_CONFIG_RESOURCE_NAME);
620 LOGGER.error(message, exception);
621 throw new PolicyConfigException(message, exception);
625 private ArrayList<PolicyConfig> configResult(final APIPolicyConfigResponse[] response)
626 throws PolicyConfigException {
627 final ArrayList<PolicyConfig> result = new ArrayList<>();
628 if (response != null) {
629 for (final APIPolicyConfigResponse policyConfigResponse : response) {
630 final StdPolicyConfig policyConfig = new StdPolicyConfig();
631 policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage());
632 policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions());
633 policyConfig.setPolicyConfigStatus(policyConfigResponse.getPolicyConfigStatus());
634 policyConfig.setPolicyName(policyConfigResponse.getPolicyName());
635 policyConfig.setPolicyType(policyConfigResponse.getType());
636 policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion());
637 policyConfig.setPolicyType(policyConfigResponse.getPolicyType());
638 policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes());
639 setMatches(policyConfig.getMatchingConditions());
640 if (policyConfigResponse.getType() != null) {
642 switch (policyConfigResponse.getType()) {
644 final StringReader reader = new StringReader(policyConfigResponse.getConfig());
645 try (final JsonReader jsonReader = Json.createReader(reader)) {
646 final JsonObject object = jsonReader.readObject();
647 policyConfig.setJsonObject(object);
651 policyConfig.setOther(policyConfigResponse.getConfig());
654 final Properties props = new Properties();
655 props.putAll(policyConfigResponse.getProperty());
656 policyConfig.setProperties(props);
659 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
660 final DocumentBuilder builder = factory.newDocumentBuilder();
661 final StringReader stringReader = new StringReader(policyConfigResponse.getConfig());
662 policyConfig.setDocument(builder.parse(new InputSource(stringReader)));
665 } catch (final Exception exception) {
666 LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + exception);
667 throw new PolicyConfigException(
668 XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", exception);
671 result.add(policyConfig);
677 private void setMatches(final Map<String, String> matchingConditions) {
678 final Matches match = new Matches();
679 final HashMap<String, String> configAttributes = new HashMap<>();
681 for (final Map.Entry<String, String> entry : matchingConditions.entrySet()) {
682 if (PolicyCommonConfigConstants.ONAP_NAME.equalsIgnoreCase(entry.getKey())) {
683 match.setOnapName(entry.getValue());
684 } else if (PolicyCommonConfigConstants.CONFIG_NAME.equalsIgnoreCase(entry.getKey())) {
685 match.setConfigName(entry.getValue());
687 configAttributes.put(entry.getKey(), entry.getValue());
690 if (!configAttributes.isEmpty()) {
691 match.setConfigAttributes(configAttributes);
693 MatchStore.storeMatch(match);
694 } catch (final Exception e) {
695 LOGGER.error("StoreMatch failed for Onap:" + match.getOnapName() + " Config: " + match.getConfigName(), e);
700 * Generic Rest Client to call PDP services.
702 <T> ResponseEntity<T> callNewPDP(final String resource, final HttpMethod method, final Object body,
703 final Class<T> responseType) throws PolicyException {
704 final RestTemplate restTemplate = new RestTemplate();
705 final HttpEntity<?> requestEntity = new HttpEntity<>(body, getHeaders());
706 ResponseEntity<T> result = null;
707 HttpClientErrorException exception = null;
709 while (pdpsCount < pdps.size()) {
711 result = restTemplate.exchange(pdps.get(0) + "/api/" + resource, method, requestEntity, responseType);
712 } catch (final HttpClientErrorException e) {
713 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
715 } catch (final Exception e) {
716 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
717 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
719 if (result == null) {
720 Collections.rotate(pdps, -1);
721 Collections.rotate(encoding, -1);
727 if (exception == null || exception.getStatusCode() == null) {
731 final String message = getHttpErrorMessage(exception, resource);
732 LOGGER.error(message);
733 throw new PolicyException(message, exception);
736 private String getHttpErrorMessage(final HttpClientErrorException exception, final String resource) {
737 if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
738 return XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + ERROR_AUTH_GET_PERM
741 if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
742 return XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":"
743 + exception.getResponseBodyAsString();
745 if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
746 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps + exception;
748 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":"
749 + exception.getResponseBodyAsString();
752 private HttpHeaders getHeaders() {
753 final HttpHeaders headers = new HttpHeaders();
754 headers.set("ClientAuth", "Basic " + clientEncoding);
755 headers.set("Authorization", "Basic " + encoding.get(0));
756 if (contentType != null) {
757 headers.set("Content-Type", contentType);
759 headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
761 headers.set("Environment", environment);
765 private static void setClientEncoding() {
766 final Base64.Encoder encoder = Base64.getEncoder();
767 clientEncoding = encoder.encodeToString((userName + ":" + pass).getBytes(StandardCharsets.UTF_8));
770 public Collection<String> listConfigImpl(final ConfigRequestParameters listRequestParameters)
771 throws PolicyConfigException {
772 final Collection<String> policyList = new ArrayList<>();
774 policyList.add(TEST_POLICY_NAME);
777 final Collection<PolicyConfig> policyConfig = getConfigImpl(listRequestParameters);
778 for (final PolicyConfig policy : policyConfig) {
779 if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains(PE300)) {
780 policyList.add(policy.getPolicyConfigMessage());
782 policyList.add("Policy Name: " + policy.getPolicyName());
788 public Collection<PolicyResponse> sendEventImpl(final Map<String, String> eventAttributes, final UUID requestID)
789 throws PolicyEventException {
793 // Long way here, can be shortened and will be done.
794 final EventRequestParameters eventRequestParameters = new EventRequestParameters();
795 eventRequestParameters.setEventAttributes(eventAttributes);
796 eventRequestParameters.setRequestID(requestID);
797 body = PolicyUtils.objectToJsonString(eventRequestParameters);
798 } catch (final JsonProcessingException e) {
799 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
800 LOGGER.error(message);
801 throw new PolicyEventException(message, e);
805 final ResponseEntity<StdPolicyResponse[]> result =
806 callNewPDP(SEND_EVENT_RESOURCE_NAME, HttpMethod.POST, body, StdPolicyResponse[].class);
808 return eventResult(result.getBody());
809 } catch (final Exception exception) {
810 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
811 final String message = getErrorMessage(exception, defaulMessage, SEND_EVENT_RESOURCE_NAME);
812 LOGGER.error(message, exception);
813 throw new PolicyEventException(message, exception);
817 private String getErrorMessage(final Exception exception, final String defaulMessage, final String resource) {
818 final Throwable cause = exception.getCause();
819 if (cause != null && cause.getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
820 return XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource;
822 if (cause != null && exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
823 return XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
825 return defaulMessage;
828 private ArrayList<PolicyResponse> eventResult(final StdPolicyResponse[] response) {
829 final ArrayList<PolicyResponse> eventResult = new ArrayList<>();
830 if (response != null && response.length > 0) {
831 for (final StdPolicyResponse policyConfigResponse : response) {
832 eventResult.add(policyConfigResponse);
838 private void setProperty(final String propertyFilePath, String clientKey) throws PolicyEngineException {
839 if (propertyFilePath == null) {
840 throw new PolicyEngineException(
841 XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided");
844 final Properties prop = getProperties(propertyFilePath);
845 // UEB and DMAAP Settings
846 final String notificationTypeValue = prop.getProperty(NOTIFICATION_TYPE_PROP_NAME);
847 final String serverList = prop.getProperty(NOTIFICATION_SERVERS_PROP_NAME);
848 topic = prop.getProperty(NOTIFICATION_TOPIC_PROP_NAME);
849 apiKey = prop.getProperty(UEB_API_KEY_PROP_NAME);
850 apiSecret = prop.getProperty(UEB_API_SECRET_PROP_NAME);
852 setNotificationType(notificationTypeValue, DEFAULT_NOTIFICATION);
854 if (serverList == null) {
855 notificationType.clear();
856 notificationType.add(DEFAULT_NOTIFICATION);
858 "Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets");
860 notificationURLList = getPropertyValueAsList(serverList.trim(), COMMA);
864 topic = topic.trim();
866 LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter.");
869 // Client ID Authorization Settings.
870 final String clientID = prop.getProperty(CLIENT_ID_PROP_NAME);
871 if (clientKey == null) {
872 clientKey = getClientKeyFromProperties(prop);
874 if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) {
875 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
876 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
877 throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS
878 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
880 setClientId(clientID.trim());
881 setClientKey(clientKey.trim());
883 setEnvironment(prop);
884 // Initializing the values.
886 readPdpProperites(prop);
887 // Get JUNIT property from properties file when running tests
891 private void readPdpProperites(final Properties prop) throws PolicyEngineException {
892 // Check the Keys for PDP_URLs
893 for (final String propertyKey : prop.stringPropertyNames()) {
894 if (propertyKey.startsWith(PDP_URL_PROP_NAME)) {
895 final String propertyValue = prop.getProperty(propertyKey);
896 if (propertyValue == null) {
897 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
898 + "Properties file doesn't have the PDP_URL parameter");
900 if (propertyValue.contains(SEMICOLLON)) {
901 final List<String> pdpDefault = Arrays.asList(propertyValue.split(REGEX));
902 for (final String pdpVal : pdpDefault) {
903 readPDPParam(pdpVal);
906 readPDPParam(propertyValue);
910 if (pdps == null || pdps.isEmpty()) {
911 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
912 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
916 private void setNotificationType(final String propertyValue, final String defaultValue) {
917 if (propertyValue == null) {
918 notificationType.add(defaultValue);
920 "Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets");
922 notificationType = getPropertyValueAsList(propertyValue.trim(), COMMA);
926 private String getClientKeyFromProperties(final Properties prop) {
927 final String clientKeyValue = prop.getProperty(CLIENT_KEY_PROP_NAME);
929 return PolicyUtils.decode(clientKeyValue);
930 } catch (UnsupportedEncodingException | IllegalArgumentException e) {
931 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
932 + " Cannot Decode the given Password Proceeding with given Password!!", e);
934 return clientKeyValue;
937 private Properties getProperties(final String propertyFilePath) throws PolicyEngineException {
938 // Adding logic for remote Properties file.
939 if (propertyFilePath.startsWith(HTTP)) {
940 return getRemoteProperties(propertyFilePath);
942 return getFileProperties(propertyFilePath);
945 private Properties getFileProperties(final String propertyFilePath) throws PolicyEngineException {
946 final Path file = Paths.get(propertyFilePath);
947 if (!file.toFile().exists()) {
948 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
949 + "File doesn't exist in the specified Path " + file.toString());
951 if (file.toString().endsWith(".properties")) {
952 try (BufferedReader bufferedReader = Files.newBufferedReader(file);) {
953 final Properties prop = new Properties();
954 prop.load(bufferedReader);
956 } catch (final IOException exception) {
957 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + exception);
958 throw new PolicyEngineException(
959 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", exception);
962 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath);
963 throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file");
966 private Properties getRemoteProperties(final String propertyFilePath) throws PolicyEngineException {
968 final URL configURL = new URL(propertyFilePath);
969 final URLConnection connection = configURL.openConnection();
970 final Properties prop = new Properties();
971 prop.load(connection.getInputStream());
973 } catch (final IOException e) {
974 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
975 throw new PolicyEngineException(
976 XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage());
980 private List<String> getPropertyValueAsList(final String propertyValue, final String split) {
981 if (propertyValue.contains(split)) {
982 return Arrays.asList(propertyValue.split(split));
984 final List<String> valuesList = new ArrayList<>();
985 valuesList.add(propertyValue);
989 private static void checkJunit(final Properties prop) {
990 final String junitFlag = prop.getProperty(JUNIT_PROP_NAME);
991 if (junitFlag == null || junitFlag.isEmpty()) {
992 LOGGER.info("No JUNIT property provided, this will not be executed as a test.");
994 if ("test".equalsIgnoreCase(junitFlag)) {
995 StdPolicyEngine.junit = true;
997 StdPolicyEngine.junit = false;
1002 private static void init() {
1003 pdps = new ArrayList<>();
1004 encoding = new ArrayList<>();
1007 private static void setEnvironment(final Properties prop) {
1008 environment = prop.getProperty(ENVIRONMENT_PROP_NAME, AAFEnvironment.DEVL.toString());
1009 if (environment.equalsIgnoreCase(AAFEnvironment.TEST.toString())) {
1010 environment = AAFEnvironment.TEST.toString();
1011 } else if (environment.equalsIgnoreCase(AAFEnvironment.PROD.toString())) {
1012 environment = AAFEnvironment.PROD.toString();
1014 environment = AAFEnvironment.DEVL.toString();
1018 private static void setClientId(final String clientID) {
1019 userName = clientID;
1023 * Read the PDP_URL parameter
1025 private void readPDPParam(final String pdpVal) throws PolicyEngineException {
1026 if (pdpVal.contains(COMMA)) {
1027 final List<String> pdpValues = Arrays.asList(pdpVal.split(PDP_VALUE_REGEX));
1028 if (pdpValues.size() == 3) {
1030 pdps.add(pdpValues.get(0));
1031 // 1:2 will be UserID:Password
1032 final String userID = pdpValues.get(1);
1033 final String userPas = pdpValues.get(2);
1034 final Base64.Encoder encoder = Base64.getEncoder();
1035 encoding.add(encoder.encodeToString((userID + ":" + userPas).getBytes(StandardCharsets.UTF_8)));
1037 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues);
1038 throw new PolicyEngineException(
1039 XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues);
1043 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal);
1044 throw new PolicyEngineException(
1045 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values.");
1050 * Allowing changes to the scheme and Handler.
1052 public void notification(final NotificationScheme scheme, final NotificationHandler handler) {
1053 this.scheme = scheme;
1054 this.handler = handler;
1055 LOGGER.debug("Scheme is : " + scheme.toString());
1056 LOGGER.debug("Handler is : " + handler.getClass().getName());
1058 if (UEB.equals(notificationType.get(0))) {
1059 if (this.uebThread) {
1060 AutoClientUEB.setAuto(scheme, handler);
1061 this.uebThread = registerUEBThread.isAlive();
1063 } else if (notificationType.get(0).equals(DMAAP)) {
1064 if (this.dmaapThread) {
1065 AutoClientDMAAP.setAuto(scheme, handler);
1066 this.dmaapThread = registerDMAAPThread.isAlive();
1069 AutoClientEnd.setAuto(scheme, handler);
1077 if (UEB.equals(notificationType.get(0)) && !this.uebThread) {
1078 this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret);
1079 AutoClientUEB.setAuto(scheme, handler);
1080 this.registerUEBThread = new Thread(this.uebClientThread);
1081 this.registerUEBThread.start();
1082 this.uebThread = true;
1083 } else if (notificationType.get(0).equals(DMAAP) && !this.dmaapThread) {
1084 this.dmaapClientThread = new AutoClientDMAAP(notificationURLList, topic, userName, pass);
1085 AutoClientDMAAP.setAuto(scheme, handler);
1086 this.registerDMAAPThread = new Thread(this.dmaapClientThread);
1087 this.registerDMAAPThread.start();
1088 this.dmaapThread = true;
1090 if (pdps.get(0) != null) {
1091 if (AutoClientEnd.getURL() == null) {
1092 AutoClientEnd.start(pdps.get(0));
1094 AutoClientEnd.stop();
1095 AutoClientEnd.start(pdps.get(0));
1103 * Gets the Notification if one exists. Used only for Manual Polling purposes.
1105 public PDPNotification getNotification() {
1106 // Check if there is proper scheme..
1107 PDPNotification notification;
1108 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)
1109 || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
1110 if (UEB.equals(notificationType.get(0))) {
1111 ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID);
1112 notification = ManualClientEndUEB.result(scheme);
1113 } else if (notificationType.get(0).equals(DMAAP)) {
1114 ManualClientEndDMAAP.start(notificationURLList, topic, UNIQUEID, userName, pass);
1115 notification = ManualClientEndDMAAP.result(scheme);
1117 ManualClientEnd.start(pdps.get(0));
1118 LOGGER.debug("manual notification requested.. : " + scheme.toString());
1119 notification = ManualClientEnd.result(scheme);
1121 if (notification == null) {
1122 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet..");
1125 return notification;
1131 * Setting the Scheme.
1133 public void setScheme(final NotificationScheme scheme) {
1134 this.scheme = scheme;
1135 if (UEB.equals(notificationType.get(0))) {
1136 AutoClientUEB.setScheme(this.scheme);
1137 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1138 ManualClientEndUEB.createTopic(pdps.get(0), UNIQUEID, notificationURLList);
1140 } else if (notificationType.get(0).equals(DMAAP)) {
1141 AutoClientDMAAP.setScheme(this.scheme);
1142 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1143 ManualClientEndDMAAP.createTopic(topic, UNIQUEID, notificationURLList, userName, pass);
1146 AutoClientEnd.setScheme(this.scheme);
1151 * Returns the Scheme
1153 public NotificationScheme getScheme() {
1158 * Returns the NotificationHandler
1160 public NotificationHandler getNotificationHandler() {
1161 return this.handler;
1165 * Stop the Notification Service if its running.
1167 public void stopNotification() {
1168 if (this.scheme != null && this.handler != null
1169 && (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)
1170 || this.scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS))) {
1171 LOGGER.info("Clear Notification called.. ");
1172 if (UEB.equals(notificationType.get(0))) {
1173 this.uebClientThread.terminate();
1174 this.uebThread = false;
1175 } else if (notificationType.get(0).equals(DMAAP)) {
1176 this.dmaapClientThread.terminate();
1177 this.dmaapThread = false;
1179 AutoClientEnd.stop();
1185 * Push a policy to the PDP API implementation
1187 public String pushPolicy(final String policyScope, final String policyName, final String policyType,
1188 final String pdpGroup, final UUID requestID) throws PolicyException {
1189 validateParameters(policyName, policyScope);
1191 final PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
1192 pushPolicyParameters.setPolicyName(policyScope + "." + policyName);
1193 pushPolicyParameters.setPolicyType(policyType);
1194 pushPolicyParameters.setPdpGroup(pdpGroup);
1195 pushPolicyParameters.setRequestID(requestID);
1196 return pushPolicyImpl(pushPolicyParameters).getResponseMessage();
1199 private boolean isNotValid(final String value) {
1200 return value == null || value.trim().isEmpty();
1203 public String createUpdateConfigPolicy(final String policyName, final String policyDescription,
1204 final String onapName, final String configName, final Map<String, String> configAttributes,
1205 final String configType, final String body, final String policyScope, final UUID requestID,
1206 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1207 final boolean updateFlag) throws PolicyException {
1208 return createUpdateConfigPolicyImpl(policyName, policyDescription, onapName, configName, configAttributes,
1209 configType, body, policyScope, requestID, riskLevel, riskType, guard, ttlDate, updateFlag);
1213 * Create Config Policy API Implementation
1215 public String createUpdateConfigPolicyImpl(final String policyName, final String policyDescription,
1216 final String onapName, final String configName, final Map<String, String> configAttributes,
1217 final String configType, final String body, final String policyScope, final UUID requestID,
1218 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1219 final boolean updateFlag) throws PolicyException {
1221 validateParameters(policyName, policyScope);
1223 final PolicyParameters policyParameters = new PolicyParameters();
1224 policyParameters.setPolicyClass(PolicyClass.Config);
1225 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
1226 policyParameters.setPolicyName(policyScope + "." + policyName);
1227 policyParameters.setPolicyDescription(policyDescription);
1228 policyParameters.setOnapName(onapName);
1229 policyParameters.setConfigName(configName);
1231 final Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
1232 attributes.put(AttributeType.MATCHING, configAttributes);
1234 policyParameters.setAttributes(attributes);
1235 policyParameters.setConfigBodyType(PolicyType.valueOf(configType));
1236 policyParameters.setConfigBody(body);
1237 policyParameters.setRequestID(requestID);
1238 policyParameters.setRiskLevel(riskLevel);
1239 policyParameters.setRiskType(riskType);
1240 policyParameters.setGuard(Boolean.parseBoolean(guard));
1241 policyParameters.setTtlDate(toDate(ttlDate));
1242 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1245 private Date toDate(final String dateString) {
1247 return new SimpleDateFormat(DATE_FORMAT).parse(dateString);
1248 } catch (final ParseException e) {
1249 LOGGER.warn("Error Parsing date given " + dateString);
1254 public String createUpdateConfigFirewallPolicy(final String policyName, final JsonObject firewallJson,
1255 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1256 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1257 return createUpdateConfigFirewallPolicyImpl(policyName, firewallJson, policyScope, requestID, riskLevel,
1258 riskType, guard, ttlDate, updateFlag);
1262 * Create Update Config Firewall Policy API implementation
1264 public String createUpdateConfigFirewallPolicyImpl(final String policyName, final JsonObject firewallJson,
1265 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1266 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1267 validateParameters(policyName, policyScope);
1269 final PolicyParameters policyParameters = new PolicyParameters();
1270 policyParameters.setPolicyClass(PolicyClass.Config);
1271 policyParameters.setPolicyConfigType(PolicyConfigType.Firewall);
1272 policyParameters.setPolicyName(policyScope + "." + policyName);
1273 policyParameters.setConfigBody(firewallJson.toString());
1274 policyParameters.setRequestID(requestID);
1275 policyParameters.setRiskLevel(riskLevel);
1276 policyParameters.setRiskType(riskType);
1277 policyParameters.setGuard(Boolean.parseBoolean(guard));
1278 policyParameters.setTtlDate(toDate(ttlDate));
1279 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1282 private void validateParameters(final String policyName, final String policyScope) throws PolicyException {
1283 if (isNotValid(policyScope)) {
1284 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
1285 LOGGER.error(message);
1286 throw new PolicyException(message);
1288 if (isNotValid(policyName)) {
1289 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
1290 LOGGER.error(message);
1291 throw new PolicyException(message);
1295 public static void setClientKey(final String clientKey) {
1296 if (clientKey != null && !clientKey.isEmpty()) {
1297 StdPolicyEngine.pass = clientKey;
1298 setClientEncoding();
1303 * Get the Environment.
1305 public static String getEnvironment() {
1310 * Rotate the PDP list upon WEBsocket Failures
1312 public static void rotatePDPList() {
1313 Collections.rotate(pdps, -1);
1314 Collections.rotate(encoding, -1);
1318 * Get the latest PDP
1320 public static String getPDPURL() {
1330 List<String> getNotificationType() {
1331 return notificationType;
1335 List<String> getNotificationURLList() {
1336 return notificationURLList;