2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
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 Property structure even if it null.
182 public StdPolicyEngine(final Properties properties, final String clientKey) throws PolicyEngineException {
183 setProperty(properties, clientKey);
187 * Taking the Notification Constructor.
189 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme,
190 final NotificationHandler handler) throws PolicyEngineException {
191 setProperty(propertyFilePath, null);
192 this.scheme = scheme;
193 this.handler = handler;
194 if ((!UEB.equals(notificationType.get(0))) || (!DMAAP.equals(notificationType.get(0)))) {
195 AutoClientEnd.setAuto(scheme, handler);
197 notification(scheme, handler);
201 * Taking the Notification Constructor.
203 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme)
204 throws PolicyEngineException {
205 setProperty(propertyFilePath, null);
206 this.scheme = scheme;
211 * sendEvent API Implementation
213 public Collection<PolicyResponse> sendEvent(final Map<String, String> eventAttributes, final UUID requestID)
214 throws PolicyEventException {
215 return sendEventImpl(eventAttributes, requestID);
219 * sendEvent API Implementation for eventRequestParameters
221 public Collection<PolicyResponse> sendEvent(final EventRequestParameters eventRequestParameters)
222 throws PolicyEventException {
223 if (eventRequestParameters == null) {
224 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. ";
225 LOGGER.error(message);
226 throw new PolicyEventException(message);
228 return sendEventImpl(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID());
232 * getConfig using configRequestParameters Implementation
234 public Collection<PolicyConfig> getConfig(final ConfigRequestParameters configRequestParameters)
235 throws PolicyConfigException {
236 return getConfigImpl(configRequestParameters);
240 * listPolicies using configRequestParameters Implementation
242 public Collection<String> listConfig(final ConfigRequestParameters listPolicyRequestParameters)
243 throws PolicyConfigException {
244 return listConfigImpl(listPolicyRequestParameters);
248 * getDecision using the decision Attributes.
250 public DecisionResponse getDecision(final String onapName, final Map<String, String> decisionAttributes,
251 final UUID requestID) throws PolicyDecisionException {
252 return getDecisionImpl(onapName, decisionAttributes, requestID);
256 * getDecision Using decisionRequestParameters.
258 public DecisionResponse getDecision(final DecisionRequestParameters decisionRequestParameters)
259 throws PolicyDecisionException {
260 if (decisionRequestParameters == null) {
261 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. ";
262 LOGGER.error(message);
263 throw new PolicyDecisionException(message);
265 return getDecisionImpl(decisionRequestParameters.getOnapName(),
266 decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID());
270 * getMetrics using metricsRequestParameters
272 public MetricsResponse getMetrics(final MetricsRequestParameters parameters) throws PolicyException {
273 return getMetricsImpl(parameters);
276 public MetricsResponse getMetricsImpl(final MetricsRequestParameters parameters) throws PolicyException {
278 // Create the Request
280 if (parameters != null) {
281 body = PolicyUtils.objectToJsonString(parameters);
283 } catch (final JsonProcessingException jsonProcessingException) {
284 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
285 LOGGER.error(message);
286 throw new PolicyException(message, jsonProcessingException);
289 final StdMetricsResponse response = new StdMetricsResponse();
292 final ResponseEntity<String> result =
293 callNewPDP(GET_METRICS_RESOURCE_NAME, HttpMethod.GET, body, String.class);
295 response.setResponseMessage(result.getBody());
296 response.setResponseCode(result.getStatusCode().value());
298 } catch (final PolicyException exception) {
299 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
300 LOGGER.error(exception);
301 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
302 response.setResponseCode(ex.getRawStatusCode());
303 response.setResponseMessage(exception.getMessage());
306 final String message =
307 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
308 LOGGER.error(message, exception);
309 throw new PolicyException(message, exception);
314 * PushPolicy using pushPolicyParameters.
316 public PolicyChangeResponse pushPolicy(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
317 return pushPolicyImpl(pushPolicyParameters);
320 public PolicyChangeResponse pushPolicyImpl(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
321 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
325 body = PolicyUtils.objectToJsonString(pushPolicyParameters);
326 } catch (final JsonProcessingException e) {
327 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
328 LOGGER.error(message);
329 throw new PolicyException(message, e);
333 final ResponseEntity<String> result =
334 callNewPDP(PUSH_POLICY_RESOURCE_NAME, HttpMethod.PUT, body, String.class);
336 response.setResponseMessage(result.getBody());
337 response.setResponseCode(result.getStatusCode().value());
339 } catch (final PolicyException exception) {
340 return processException(exception);
345 * Delete a Policy using deletePolicyParameters
347 public PolicyChangeResponse deletePolicy(final DeletePolicyParameters parameters) throws PolicyException {
348 return deletePolicyImpl(parameters);
351 public PolicyChangeResponse deletePolicyImpl(final DeletePolicyParameters parameters) throws PolicyException {
352 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
356 body = PolicyUtils.objectToJsonString(parameters);
357 } catch (final JsonProcessingException e) {
358 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
359 LOGGER.error(message);
360 throw new PolicyException(message, e);
364 final ResponseEntity<String> result =
365 callNewPDP(DELETE_POLICY_RESOURCE_NAME, HttpMethod.DELETE, body, String.class);
367 response.setResponseMessage(result.getBody());
368 response.setResponseCode(result.getStatusCode().value());
369 } catch (final PolicyException exception) {
370 return processException(exception);
376 * getDictionaryItem Using dictionaryParameters
378 public DictionaryResponse getDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
379 return getDictionaryItemImpl(parameters);
382 public DictionaryResponse getDictionaryItemImpl(final DictionaryParameters parameters) throws PolicyException {
383 final StdDictionaryResponse response = new StdDictionaryResponse();
387 body = PolicyUtils.objectToJsonString(parameters);
388 } catch (final JsonProcessingException e) {
389 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
390 LOGGER.error(message);
391 throw new PolicyException(message, e);
395 final ResponseEntity<APIDictionaryResponse> result =
396 callNewPDP(GET_DICTIONARY_ITEMS_RESOURCE_NAME, HttpMethod.POST, body, APIDictionaryResponse.class);
398 return dictionaryResult(result.getBody());
399 } catch (final Exception exception) {
400 if (exception.getCause().getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
401 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM
402 + GET_DICTIONARY_ITEMS_RESOURCE_NAME;
403 LOGGER.error(message);
404 response.setResponseMessage(message);
405 response.setResponseCode(HttpStatus.UNAUTHORIZED.value());
408 if (exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
409 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
410 response.setResponseMessage(message);
411 response.setResponseCode(HttpStatus.BAD_REQUEST.value());
414 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
415 LOGGER.error(message, exception);
416 response.setResponseMessage(message);
417 response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
422 @SuppressWarnings("unchecked")
423 private StdDictionaryResponse dictionaryResult(final APIDictionaryResponse body) {
424 final StdDictionaryResponse response = new StdDictionaryResponse();
425 response.setResponseCode(body.getResponseCode());
426 response.setResponseMessage(body.getResponseMessage());
427 response.setDictionaryData((Map<String, String>) body.getDictionaryData());
428 if (body.getDictionaryJson() != null) {
429 final Gson objGson = new GsonBuilder().create();
430 final String mapToJson = objGson.toJson(body.getDictionaryJson());
431 try (final JsonReader jsonReader = Json.createReader(new StringReader(mapToJson));) {
432 final JsonObject object = jsonReader.readObject();
433 response.setDictionaryJson(object);
440 * createDictinaryItem Using dictionaryParameters.
442 public PolicyChangeResponse createDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
443 return createUpdateDictionaryItemImpl(parameters, false);
447 * updateDictinaryItem Using dictionaryParameters.
449 public PolicyChangeResponse updateDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
450 return createUpdateDictionaryItemImpl(parameters, true);
453 public PolicyChangeResponse createUpdateDictionaryItemImpl(final DictionaryParameters parameters,
454 final boolean updateFlag) throws PolicyException {
456 final String resource = getDictionaryResouceName(updateFlag);
460 body = PolicyUtils.objectToJsonString(parameters);
461 } catch (final JsonProcessingException jsonProcessingException) {
462 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
463 LOGGER.error(message);
464 throw new PolicyException(message, jsonProcessingException);
468 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
469 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
471 response.setResponseMessage(result.getBody());
472 response.setResponseCode(result.getStatusCode().value());
474 } catch (final PolicyException exception) {
475 return processException(exception);
479 private String getDictionaryResouceName(final boolean updateFlag) {
480 return updateFlag ? UPDATE_DICTIONARY_ITEM_RESOURCE_NAME : CREATE_DICTIONARY_ITEM_RESOURCE_NAME;
484 * PolicyEngine Import
486 public PolicyChangeResponse policyEngineImport(final ImportParameters importParameters) throws PolicyException {
487 return policyEngineImportImpl(importParameters);
490 public PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters) throws PolicyException {
491 final LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
494 final String body = PolicyUtils.objectToJsonString(importParameters);
495 parameters.set("importParametersJson", body);
496 parameters.set("file", new FileSystemResource(importParameters.getFilePath()));
497 } catch (final Exception e) {
498 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
499 LOGGER.error(message);
500 throw new PolicyException(message, e);
502 contentType = MediaType.MULTIPART_FORM_DATA_VALUE;
505 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
506 final ResponseEntity<String> result =
507 callNewPDP(POLICY_ENGINE_IMPORT_RESOURCE_NAME, HttpMethod.POST, parameters, String.class);
509 response.setResponseMessage(result.getBody());
510 response.setResponseCode(result.getStatusCode().value());
512 } catch (final PolicyException exception) {
513 return processException(exception);
520 * createPolicy Using policyParameters.
522 public PolicyChangeResponse createPolicy(final PolicyParameters policyParameters) throws PolicyException {
523 return createUpdatePolicyImpl(policyParameters, false);
527 * updatePolicy using policyParameters.
529 public PolicyChangeResponse updatePolicy(final PolicyParameters policyParameters) throws PolicyException {
530 return createUpdatePolicyImpl(policyParameters, true);
533 public PolicyChangeResponse createUpdatePolicyImpl(final PolicyParameters policyParameters,
534 final boolean updateFlag) throws PolicyException {
535 final String resource = getPolicyResourceName(updateFlag);
539 body = PolicyUtils.objectToJsonString(policyParameters);
540 } catch (final JsonProcessingException e) {
541 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
542 LOGGER.error(message);
543 throw new PolicyException(message, e);
547 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
548 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
550 response.setResponseMessage(result.getBody());
551 response.setResponseCode(result.getStatusCode().value());
553 } catch (final PolicyException exception) {
554 return processException(exception);
558 private String getPolicyResourceName(final boolean updateFlag) {
559 return updateFlag ? UPDATE_POLICY_RESOURCE_NAME : CREATE_POLICY_RESOURCE_NAME;
562 private PolicyChangeResponse processException(final PolicyException exception) throws PolicyException {
563 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
564 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
565 LOGGER.error(exception);
566 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
567 response.setResponseCode(ex.getRawStatusCode());
568 response.setResponseMessage(exception.getMessage());
571 final String message =
572 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
573 LOGGER.error(message, exception);
574 throw new PolicyException(message, exception);
578 public DecisionResponse getDecisionImpl(final String onapName, final Map<String, String> decisionAttributes,
579 final UUID requestID) throws PolicyDecisionException {
583 final DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters();
584 decisionRequestParameters.setDecisionAttributes(decisionAttributes);
585 decisionRequestParameters.setOnapName(onapName);
586 decisionRequestParameters.setRequestID(requestID);
587 body = PolicyUtils.objectToJsonString(decisionRequestParameters);
588 } catch (final JsonProcessingException e) {
589 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
590 LOGGER.error(message);
591 throw new PolicyDecisionException(message, e);
595 final ResponseEntity<StdDecisionResponse> result =
596 callNewPDP(GET_DECISION_RESOURCE_NAME, HttpMethod.POST, body, StdDecisionResponse.class);
598 return result.getBody();
599 } catch (final Exception exception) {
600 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
601 final String message = getErrorMessage(exception, defaulMessage, GET_DECISION_RESOURCE_NAME);
602 LOGGER.error(message, exception);
603 throw new PolicyDecisionException(message, exception);
607 public Collection<PolicyConfig> getConfigImpl(final ConfigRequestParameters configRequestParameters)
608 throws PolicyConfigException {
612 body = PolicyUtils.objectToJsonString(configRequestParameters);
613 } catch (final JsonProcessingException e) {
614 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
615 LOGGER.error(message);
616 throw new PolicyConfigException(message, e);
620 final ResponseEntity<APIPolicyConfigResponse[]> result =
621 callNewPDP(GET_CONFIG_RESOURCE_NAME, HttpMethod.POST, body, APIPolicyConfigResponse[].class);
623 return configResult(result.getBody());
624 } catch (final Exception exception) {
625 final String defaulMessage = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS + pdps;
626 final String message = getErrorMessage(exception, defaulMessage, GET_CONFIG_RESOURCE_NAME);
627 LOGGER.error(message, exception);
628 throw new PolicyConfigException(message, exception);
632 private ArrayList<PolicyConfig> configResult(final APIPolicyConfigResponse[] response)
633 throws PolicyConfigException {
634 final ArrayList<PolicyConfig> result = new ArrayList<>();
635 if (response != null) {
636 for (final APIPolicyConfigResponse policyConfigResponse : response) {
637 final StdPolicyConfig policyConfig = new StdPolicyConfig();
638 policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage());
639 policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions());
640 policyConfig.setPolicyConfigStatus(policyConfigResponse.getPolicyConfigStatus());
641 policyConfig.setPolicyName(policyConfigResponse.getPolicyName());
642 policyConfig.setPolicyType(policyConfigResponse.getType());
643 policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion());
644 policyConfig.setPolicyType(policyConfigResponse.getPolicyType());
645 policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes());
646 setMatches(policyConfig.getMatchingConditions());
647 if (policyConfigResponse.getType() != null) {
649 switch (policyConfigResponse.getType()) {
651 final StringReader reader = new StringReader(policyConfigResponse.getConfig());
652 try (final JsonReader jsonReader = Json.createReader(reader)) {
653 final JsonObject object = jsonReader.readObject();
654 policyConfig.setJsonObject(object);
658 policyConfig.setOther(policyConfigResponse.getConfig());
661 final Properties props = new Properties();
662 props.putAll(policyConfigResponse.getProperty());
663 policyConfig.setProperties(props);
666 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
667 final DocumentBuilder builder = factory.newDocumentBuilder();
668 final StringReader stringReader = new StringReader(policyConfigResponse.getConfig());
669 policyConfig.setDocument(builder.parse(new InputSource(stringReader)));
672 } catch (final Exception exception) {
673 LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + exception);
674 throw new PolicyConfigException(
675 XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", exception);
678 result.add(policyConfig);
684 private void setMatches(final Map<String, String> matchingConditions) {
685 final Matches match = new Matches();
686 final HashMap<String, String> configAttributes = new HashMap<>();
688 for (final Map.Entry<String, String> entry : matchingConditions.entrySet()) {
689 if (PolicyCommonConfigConstants.ONAP_NAME.equalsIgnoreCase(entry.getKey())) {
690 match.setOnapName(entry.getValue());
691 } else if (PolicyCommonConfigConstants.CONFIG_NAME.equalsIgnoreCase(entry.getKey())) {
692 match.setConfigName(entry.getValue());
694 configAttributes.put(entry.getKey(), entry.getValue());
697 if (!configAttributes.isEmpty()) {
698 match.setConfigAttributes(configAttributes);
700 MatchStore.storeMatch(match);
701 } catch (final Exception e) {
702 LOGGER.error("StoreMatch failed for Onap:" + match.getOnapName() + " Config: " + match.getConfigName(), e);
707 * Generic Rest Client to call PDP services.
709 <T> ResponseEntity<T> callNewPDP(final String resource, final HttpMethod method, final Object body,
710 final Class<T> responseType) throws PolicyException {
711 final RestTemplate restTemplate = new RestTemplate();
712 final HttpEntity<?> requestEntity = new HttpEntity<>(body, getHeaders());
713 ResponseEntity<T> result = null;
714 HttpClientErrorException exception = null;
716 while (pdpsCount < pdps.size()) {
718 result = restTemplate.exchange(pdps.get(0) + "/api/" + resource, method, requestEntity, responseType);
719 } catch (final HttpClientErrorException e) {
720 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
722 } catch (final Exception e) {
723 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
724 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
726 if (result == null) {
727 Collections.rotate(pdps, -1);
728 Collections.rotate(encoding, -1);
734 if (exception == null || exception.getStatusCode() == null) {
738 final String message = getHttpErrorMessage(exception, resource);
739 LOGGER.error(message);
740 throw new PolicyException(message, exception);
743 private String getHttpErrorMessage(final HttpClientErrorException exception, final String resource) {
744 if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
745 return XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + ERROR_AUTH_GET_PERM
748 if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
749 return XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":"
750 + exception.getResponseBodyAsString();
752 if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
753 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps + exception;
755 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":"
756 + exception.getResponseBodyAsString();
759 private HttpHeaders getHeaders() {
760 final HttpHeaders headers = new HttpHeaders();
761 headers.set("ClientAuth", "Basic " + clientEncoding);
762 headers.set("Authorization", "Basic " + encoding.get(0));
763 if (contentType != null) {
764 headers.set("Content-Type", contentType);
766 headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
768 headers.set("Environment", environment);
772 private static void setClientEncoding() {
773 final Base64.Encoder encoder = Base64.getEncoder();
774 clientEncoding = encoder.encodeToString((userName + ":" + pass).getBytes(StandardCharsets.UTF_8));
777 public Collection<String> listConfigImpl(final ConfigRequestParameters listRequestParameters)
778 throws PolicyConfigException {
779 final Collection<String> policyList = new ArrayList<>();
781 policyList.add(TEST_POLICY_NAME);
784 final Collection<PolicyConfig> policyConfig = getConfigImpl(listRequestParameters);
785 for (final PolicyConfig policy : policyConfig) {
786 if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains(PE300)) {
787 policyList.add(policy.getPolicyConfigMessage());
789 policyList.add("Policy Name: " + policy.getPolicyName());
795 public Collection<PolicyResponse> sendEventImpl(final Map<String, String> eventAttributes, final UUID requestID)
796 throws PolicyEventException {
800 // Long way here, can be shortened and will be done.
801 final EventRequestParameters eventRequestParameters = new EventRequestParameters();
802 eventRequestParameters.setEventAttributes(eventAttributes);
803 eventRequestParameters.setRequestID(requestID);
804 body = PolicyUtils.objectToJsonString(eventRequestParameters);
805 } catch (final JsonProcessingException e) {
806 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
807 LOGGER.error(message);
808 throw new PolicyEventException(message, e);
812 final ResponseEntity<StdPolicyResponse[]> result =
813 callNewPDP(SEND_EVENT_RESOURCE_NAME, HttpMethod.POST, body, StdPolicyResponse[].class);
815 return eventResult(result.getBody());
816 } catch (final Exception exception) {
817 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
818 final String message = getErrorMessage(exception, defaulMessage, SEND_EVENT_RESOURCE_NAME);
819 LOGGER.error(message, exception);
820 throw new PolicyEventException(message, exception);
824 private String getErrorMessage(final Exception exception, final String defaulMessage, final String resource) {
825 final Throwable cause = exception.getCause();
826 if (cause != null && cause.getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
827 return XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource;
829 if (cause != null && exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
830 return XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
832 return defaulMessage;
835 private ArrayList<PolicyResponse> eventResult(final StdPolicyResponse[] response) {
836 final ArrayList<PolicyResponse> eventResult = new ArrayList<>();
837 if (response != null && response.length > 0) {
838 for (final StdPolicyResponse policyConfigResponse : response) {
839 eventResult.add(policyConfigResponse);
845 private void setProperty(final String propertyFilePath, String clientKey) throws PolicyEngineException {
846 if (propertyFilePath == null) {
847 throw new PolicyEngineException(
848 XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided");
850 final Properties prop = getProperties(propertyFilePath);
851 setProperty(prop,clientKey);
854 private void setProperty(final Properties properties, String clientKey) throws PolicyEngineException {
855 if (properties == null) {
856 throw new PolicyEngineException(
857 XACMLErrorConstants.ERROR_DATA_ISSUE + "NO properties provided, the value is NULL");
860 // UEB and DMAAP Settings
861 final String notificationTypeValue = properties.getProperty(NOTIFICATION_TYPE_PROP_NAME);
862 final String serverList = properties.getProperty(NOTIFICATION_SERVERS_PROP_NAME);
863 topic = properties.getProperty(NOTIFICATION_TOPIC_PROP_NAME);
864 apiKey = properties.getProperty(UEB_API_KEY_PROP_NAME);
865 apiSecret = properties.getProperty(UEB_API_SECRET_PROP_NAME);
867 setNotificationType(notificationTypeValue, DEFAULT_NOTIFICATION);
869 if (serverList == null) {
870 notificationType.clear();
871 notificationType.add(DEFAULT_NOTIFICATION);
873 "Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets");
875 notificationURLList = getPropertyValueAsList(serverList.trim(), COMMA);
879 topic = topic.trim();
881 LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter.");
884 // Client ID Authorization Settings.
885 final String clientID = properties.getProperty(CLIENT_ID_PROP_NAME);
886 if (clientKey == null) {
887 clientKey = getClientKeyFromProperties(properties);
889 if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) {
890 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
891 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
892 throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS
893 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
895 setClientId(clientID.trim());
896 setClientKey(clientKey.trim());
898 setEnvironment(properties);
899 // Initializing the values.
901 readPdpProperites(properties);
902 // Get JUNIT property from properties file when running tests
903 checkJunit(properties);
906 private void readPdpProperites(final Properties prop) throws PolicyEngineException {
907 // Check the Keys for PDP_URLs
908 for (final String propertyKey : prop.stringPropertyNames()) {
909 if (propertyKey.startsWith(PDP_URL_PROP_NAME)) {
910 final String propertyValue = prop.getProperty(propertyKey);
911 if (propertyValue == null) {
912 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
913 + "Properties file doesn't have the PDP_URL parameter");
915 if (propertyValue.contains(SEMICOLLON)) {
916 final List<String> pdpDefault = Arrays.asList(propertyValue.split(REGEX));
917 for (final String pdpVal : pdpDefault) {
918 readPDPParam(pdpVal);
921 readPDPParam(propertyValue);
925 if (pdps == null || pdps.isEmpty()) {
926 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
927 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
931 private void setNotificationType(final String propertyValue, final String defaultValue) {
932 if (propertyValue == null) {
933 notificationType.add(defaultValue);
935 "Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets");
937 notificationType = getPropertyValueAsList(propertyValue.trim(), COMMA);
941 private String getClientKeyFromProperties(final Properties prop) {
942 final String clientKeyValue = prop.getProperty(CLIENT_KEY_PROP_NAME);
944 return PolicyUtils.decode(clientKeyValue);
945 } catch (UnsupportedEncodingException | IllegalArgumentException e) {
946 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
947 + " Cannot Decode the given Password Proceeding with given Password!!", e);
949 return clientKeyValue;
952 private Properties getProperties(final String propertyFilePath) throws PolicyEngineException {
953 // Adding logic for remote Properties file.
954 if (propertyFilePath.startsWith(HTTP)) {
955 return getRemoteProperties(propertyFilePath);
957 return getFileProperties(propertyFilePath);
960 private Properties getFileProperties(final String propertyFilePath) throws PolicyEngineException {
961 final Path file = Paths.get(propertyFilePath);
962 if (!file.toFile().exists()) {
963 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
964 + "File doesn't exist in the specified Path " + file.toString());
966 if (file.toString().endsWith(".properties")) {
967 try (BufferedReader bufferedReader = Files.newBufferedReader(file);) {
968 final Properties prop = new Properties();
969 prop.load(bufferedReader);
971 } catch (final IOException exception) {
972 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + exception);
973 throw new PolicyEngineException(
974 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", exception);
977 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath);
978 throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file");
981 private Properties getRemoteProperties(final String propertyFilePath) throws PolicyEngineException {
983 final URL configURL = new URL(propertyFilePath);
984 final URLConnection connection = configURL.openConnection();
985 final Properties prop = new Properties();
986 prop.load(connection.getInputStream());
988 } catch (final IOException e) {
989 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
990 throw new PolicyEngineException(
991 XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage());
995 private List<String> getPropertyValueAsList(final String propertyValue, final String split) {
996 if (propertyValue.contains(split)) {
997 return Arrays.asList(propertyValue.split(split));
999 final List<String> valuesList = new ArrayList<>();
1000 valuesList.add(propertyValue);
1004 private static void checkJunit(final Properties prop) {
1005 final String junitFlag = prop.getProperty(JUNIT_PROP_NAME);
1006 if (junitFlag == null || junitFlag.isEmpty()) {
1007 LOGGER.info("No JUNIT property provided, this will not be executed as a test.");
1009 if ("test".equalsIgnoreCase(junitFlag)) {
1010 StdPolicyEngine.junit = true;
1012 StdPolicyEngine.junit = false;
1017 private static void init() {
1018 pdps = new ArrayList<>();
1019 encoding = new ArrayList<>();
1022 private static void setEnvironment(final Properties prop) {
1023 environment = prop.getProperty(ENVIRONMENT_PROP_NAME, AAFEnvironment.DEVL.toString());
1024 if (environment.equalsIgnoreCase(AAFEnvironment.TEST.toString())) {
1025 environment = AAFEnvironment.TEST.toString();
1026 } else if (environment.equalsIgnoreCase(AAFEnvironment.PROD.toString())) {
1027 environment = AAFEnvironment.PROD.toString();
1029 environment = AAFEnvironment.DEVL.toString();
1033 private static void setClientId(final String clientID) {
1034 userName = clientID;
1038 * Read the PDP_URL parameter
1040 private void readPDPParam(final String pdpVal) throws PolicyEngineException {
1041 if (pdpVal.contains(COMMA)) {
1042 final List<String> pdpValues = Arrays.asList(pdpVal.split(PDP_VALUE_REGEX));
1043 if (pdpValues.size() == 3) {
1045 pdps.add(pdpValues.get(0));
1046 // 1:2 will be UserID:Password
1047 final String userID = pdpValues.get(1);
1048 final String userPas = pdpValues.get(2);
1049 final Base64.Encoder encoder = Base64.getEncoder();
1050 encoding.add(encoder.encodeToString((userID + ":" + userPas).getBytes(StandardCharsets.UTF_8)));
1052 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues);
1053 throw new PolicyEngineException(
1054 XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues);
1058 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal);
1059 throw new PolicyEngineException(
1060 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values.");
1065 * Allowing changes to the scheme and Handler.
1067 public void notification(final NotificationScheme scheme, final NotificationHandler handler) {
1068 this.scheme = scheme;
1069 this.handler = handler;
1070 LOGGER.debug("Scheme is : " + scheme.toString());
1071 LOGGER.debug("Handler is : " + handler.getClass().getName());
1073 if (UEB.equals(notificationType.get(0))) {
1074 if (this.uebThread) {
1075 AutoClientUEB.setAuto(scheme, handler);
1076 this.uebThread = registerUEBThread.isAlive();
1078 } else if (notificationType.get(0).equals(DMAAP)) {
1079 if (this.dmaapThread) {
1080 AutoClientDMAAP.setAuto(scheme, handler);
1081 this.dmaapThread = registerDMAAPThread.isAlive();
1084 AutoClientEnd.setAuto(scheme, handler);
1092 if (UEB.equals(notificationType.get(0)) && !this.uebThread) {
1093 this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret);
1094 AutoClientUEB.setAuto(scheme, handler);
1095 this.registerUEBThread = new Thread(this.uebClientThread);
1096 this.registerUEBThread.start();
1097 this.uebThread = true;
1098 } else if (notificationType.get(0).equals(DMAAP) && !this.dmaapThread) {
1099 this.dmaapClientThread = new AutoClientDMAAP(notificationURLList, topic, userName, pass);
1100 AutoClientDMAAP.setAuto(scheme, handler);
1101 this.registerDMAAPThread = new Thread(this.dmaapClientThread);
1102 this.registerDMAAPThread.start();
1103 this.dmaapThread = true;
1105 if (pdps.get(0) != null) {
1106 if (AutoClientEnd.getURL() == null) {
1107 AutoClientEnd.start(pdps.get(0));
1109 AutoClientEnd.stop();
1110 AutoClientEnd.start(pdps.get(0));
1118 * Gets the Notification if one exists. Used only for Manual Polling purposes.
1120 public PDPNotification getNotification() {
1121 // Check if there is proper scheme..
1122 PDPNotification notification;
1123 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)
1124 || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
1125 if (UEB.equals(notificationType.get(0))) {
1126 ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID);
1127 notification = ManualClientEndUEB.result(scheme);
1128 } else if (notificationType.get(0).equals(DMAAP)) {
1129 ManualClientEndDMAAP.start(notificationURLList, topic, UNIQUEID, userName, pass);
1130 notification = ManualClientEndDMAAP.result(scheme);
1132 ManualClientEnd.start(pdps.get(0));
1133 LOGGER.debug("manual notification requested.. : " + scheme.toString());
1134 notification = ManualClientEnd.result(scheme);
1136 if (notification == null) {
1137 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet..");
1140 return notification;
1146 * Setting the Scheme.
1148 public void setScheme(final NotificationScheme scheme) {
1149 this.scheme = scheme;
1150 if (UEB.equals(notificationType.get(0))) {
1151 AutoClientUEB.setScheme(this.scheme);
1152 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1153 ManualClientEndUEB.createTopic(pdps.get(0), UNIQUEID, notificationURLList);
1155 } else if (notificationType.get(0).equals(DMAAP)) {
1156 AutoClientDMAAP.setScheme(this.scheme);
1157 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1158 ManualClientEndDMAAP.createTopic(topic, UNIQUEID, notificationURLList, userName, pass);
1161 AutoClientEnd.setScheme(this.scheme);
1166 * Returns the Scheme
1168 public NotificationScheme getScheme() {
1173 * Returns the NotificationHandler
1175 public NotificationHandler getNotificationHandler() {
1176 return this.handler;
1180 * Stop the Notification Service if its running.
1182 public void stopNotification() {
1183 if (this.scheme != null && this.handler != null
1184 && (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)
1185 || this.scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS))) {
1186 LOGGER.info("Clear Notification called.. ");
1187 if (UEB.equals(notificationType.get(0))) {
1188 this.uebClientThread.terminate();
1189 this.uebThread = false;
1190 } else if (notificationType.get(0).equals(DMAAP)) {
1191 this.dmaapClientThread.terminate();
1192 this.dmaapThread = false;
1194 AutoClientEnd.stop();
1200 * Push a policy to the PDP API implementation
1202 public String pushPolicy(final String policyScope, final String policyName, final String policyType,
1203 final String pdpGroup, final UUID requestID) throws PolicyException {
1204 validateParameters(policyName, policyScope);
1206 final PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
1207 pushPolicyParameters.setPolicyName(policyScope + "." + policyName);
1208 pushPolicyParameters.setPolicyType(policyType);
1209 pushPolicyParameters.setPdpGroup(pdpGroup);
1210 pushPolicyParameters.setRequestID(requestID);
1211 return pushPolicyImpl(pushPolicyParameters).getResponseMessage();
1214 private boolean isNotValid(final String value) {
1215 return value == null || value.trim().isEmpty();
1218 public String createUpdateConfigPolicy(final String policyName, final String policyDescription,
1219 final String onapName, final String configName, final Map<String, String> configAttributes,
1220 final String configType, final String body, final String policyScope, final UUID requestID,
1221 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1222 final boolean updateFlag) throws PolicyException {
1223 return createUpdateConfigPolicyImpl(policyName, policyDescription, onapName, configName, configAttributes,
1224 configType, body, policyScope, requestID, riskLevel, riskType, guard, ttlDate, updateFlag);
1228 * Create Config Policy API Implementation
1230 public String createUpdateConfigPolicyImpl(final String policyName, final String policyDescription,
1231 final String onapName, final String configName, final Map<String, String> configAttributes,
1232 final String configType, final String body, final String policyScope, final UUID requestID,
1233 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1234 final boolean updateFlag) throws PolicyException {
1236 validateParameters(policyName, policyScope);
1238 final PolicyParameters policyParameters = new PolicyParameters();
1239 policyParameters.setPolicyClass(PolicyClass.Config);
1240 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
1241 policyParameters.setPolicyName(policyScope + "." + policyName);
1242 policyParameters.setPolicyDescription(policyDescription);
1243 policyParameters.setOnapName(onapName);
1244 policyParameters.setConfigName(configName);
1246 final Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
1247 attributes.put(AttributeType.MATCHING, configAttributes);
1249 policyParameters.setAttributes(attributes);
1250 policyParameters.setConfigBodyType(PolicyType.valueOf(configType));
1251 policyParameters.setConfigBody(body);
1252 policyParameters.setRequestID(requestID);
1253 policyParameters.setRiskLevel(riskLevel);
1254 policyParameters.setRiskType(riskType);
1255 policyParameters.setGuard(Boolean.parseBoolean(guard));
1256 policyParameters.setTtlDate(toDate(ttlDate));
1257 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1260 private Date toDate(final String dateString) {
1262 return new SimpleDateFormat(DATE_FORMAT).parse(dateString);
1263 } catch (final ParseException e) {
1264 LOGGER.warn("Error Parsing date given " + dateString);
1269 public String createUpdateConfigFirewallPolicy(final String policyName, final JsonObject firewallJson,
1270 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1271 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1272 return createUpdateConfigFirewallPolicyImpl(policyName, firewallJson, policyScope, requestID, riskLevel,
1273 riskType, guard, ttlDate, updateFlag);
1277 * Create Update Config Firewall Policy API implementation
1279 public String createUpdateConfigFirewallPolicyImpl(final String policyName, final JsonObject firewallJson,
1280 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1281 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1282 validateParameters(policyName, policyScope);
1284 final PolicyParameters policyParameters = new PolicyParameters();
1285 policyParameters.setPolicyClass(PolicyClass.Config);
1286 policyParameters.setPolicyConfigType(PolicyConfigType.Firewall);
1287 policyParameters.setPolicyName(policyScope + "." + policyName);
1288 policyParameters.setConfigBody(firewallJson.toString());
1289 policyParameters.setRequestID(requestID);
1290 policyParameters.setRiskLevel(riskLevel);
1291 policyParameters.setRiskType(riskType);
1292 policyParameters.setGuard(Boolean.parseBoolean(guard));
1293 policyParameters.setTtlDate(toDate(ttlDate));
1294 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1297 private void validateParameters(final String policyName, final String policyScope) throws PolicyException {
1298 if (isNotValid(policyScope)) {
1299 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
1300 LOGGER.error(message);
1301 throw new PolicyException(message);
1303 if (isNotValid(policyName)) {
1304 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
1305 LOGGER.error(message);
1306 throw new PolicyException(message);
1310 public static void setClientKey(final String clientKey) {
1311 if (clientKey != null && !clientKey.isEmpty()) {
1312 StdPolicyEngine.pass = clientKey;
1313 setClientEncoding();
1318 * Get the Environment.
1320 public static String getEnvironment() {
1325 * Rotate the PDP list upon WEBsocket Failures
1327 public static void rotatePDPList() {
1328 Collections.rotate(pdps, -1);
1329 Collections.rotate(encoding, -1);
1333 * Get the latest PDP
1335 public static String getPDPURL() {
1345 List<String> getNotificationType() {
1346 return notificationType;
1350 List<String> getNotificationURLList() {
1351 return notificationURLList;