2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved.
6 * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.std;
24 import static org.onap.policy.std.utils.PolicyConfigConstants.BAD_REQUEST_STATUS_CODE;
25 import static org.onap.policy.std.utils.PolicyConfigConstants.CLIENT_ID_PROP_NAME;
26 import static org.onap.policy.std.utils.PolicyConfigConstants.CLIENT_KEY_PROP_NAME;
27 import static org.onap.policy.std.utils.PolicyConfigConstants.COMMA;
28 import static org.onap.policy.std.utils.PolicyConfigConstants.CREATE_DICTIONARY_ITEM_RESOURCE_NAME;
29 import static org.onap.policy.std.utils.PolicyConfigConstants.CREATE_POLICY_RESOURCE_NAME;
30 import static org.onap.policy.std.utils.PolicyConfigConstants.DATE_FORMAT;
31 import static org.onap.policy.std.utils.PolicyConfigConstants.DEFAULT_NOTIFICATION;
32 import static org.onap.policy.std.utils.PolicyConfigConstants.DELETE_POLICY_RESOURCE_NAME;
33 import static org.onap.policy.std.utils.PolicyConfigConstants.DMAAP;
34 import static org.onap.policy.std.utils.PolicyConfigConstants.ENVIRONMENT_PROP_NAME;
35 import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_AUTH_GET_PERM;
36 import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_DATA_ISSUE;
37 import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_INVALID_PDPS;
38 import static org.onap.policy.std.utils.PolicyConfigConstants.ERROR_WHILE_CONNECTING;
39 import static org.onap.policy.std.utils.PolicyConfigConstants.GET_CONFIG_RESOURCE_NAME;
40 import static org.onap.policy.std.utils.PolicyConfigConstants.GET_DECISION_RESOURCE_NAME;
41 import static org.onap.policy.std.utils.PolicyConfigConstants.GET_DICTIONARY_ITEMS_RESOURCE_NAME;
42 import static org.onap.policy.std.utils.PolicyConfigConstants.GET_METRICS_RESOURCE_NAME;
43 import static org.onap.policy.std.utils.PolicyConfigConstants.HTTP;
44 import static org.onap.policy.std.utils.PolicyConfigConstants.JUNIT_PROP_NAME;
45 import static org.onap.policy.std.utils.PolicyConfigConstants.NOTIFICATION_SERVERS_PROP_NAME;
46 import static org.onap.policy.std.utils.PolicyConfigConstants.NOTIFICATION_TOPIC_PROP_NAME;
47 import static org.onap.policy.std.utils.PolicyConfigConstants.NOTIFICATION_TYPE_PROP_NAME;
48 import static org.onap.policy.std.utils.PolicyConfigConstants.PDP_URL_PROP_NAME;
49 import static org.onap.policy.std.utils.PolicyConfigConstants.PDP_VALUE_REGEX;
50 import static org.onap.policy.std.utils.PolicyConfigConstants.PE300;
51 import static org.onap.policy.std.utils.PolicyConfigConstants.POLICY_ENGINE_IMPORT_RESOURCE_NAME;
52 import static org.onap.policy.std.utils.PolicyConfigConstants.PUSH_POLICY_RESOURCE_NAME;
53 import static org.onap.policy.std.utils.PolicyConfigConstants.REGEX;
54 import static org.onap.policy.std.utils.PolicyConfigConstants.SEMICOLLON;
55 import static org.onap.policy.std.utils.PolicyConfigConstants.SEND_EVENT_RESOURCE_NAME;
56 import static org.onap.policy.std.utils.PolicyConfigConstants.TEST_POLICY_NAME;
57 import static org.onap.policy.std.utils.PolicyConfigConstants.UEB;
58 import static org.onap.policy.std.utils.PolicyConfigConstants.UEB_API_KEY_PROP_NAME;
59 import static org.onap.policy.std.utils.PolicyConfigConstants.UEB_API_SECRET_PROP_NAME;
60 import static org.onap.policy.std.utils.PolicyConfigConstants.UNAUTHORIZED_STATUS_CODE;
61 import static org.onap.policy.std.utils.PolicyConfigConstants.UPDATE_DICTIONARY_ITEM_RESOURCE_NAME;
62 import static org.onap.policy.std.utils.PolicyConfigConstants.UPDATE_POLICY_RESOURCE_NAME;
63 import java.io.BufferedReader;
64 import java.io.IOException;
65 import java.io.StringReader;
66 import java.io.UnsupportedEncodingException;
68 import java.net.URLConnection;
69 import java.nio.charset.StandardCharsets;
70 import java.nio.file.Files;
71 import java.nio.file.Path;
72 import java.nio.file.Paths;
73 import java.text.ParseException;
74 import java.text.SimpleDateFormat;
75 import java.util.ArrayList;
76 import java.util.Arrays;
77 import java.util.Base64;
78 import java.util.Collection;
79 import java.util.Collections;
80 import java.util.Date;
81 import java.util.HashMap;
82 import java.util.List;
84 import java.util.Properties;
85 import java.util.UUID;
86 import javax.json.Json;
87 import javax.json.JsonObject;
88 import javax.json.JsonReader;
89 import javax.xml.parsers.DocumentBuilder;
90 import javax.xml.parsers.DocumentBuilderFactory;
91 import org.onap.policy.api.AttributeType;
92 import org.onap.policy.api.ConfigRequestParameters;
93 import org.onap.policy.api.DecisionRequestParameters;
94 import org.onap.policy.api.DecisionResponse;
95 import org.onap.policy.api.DeletePolicyParameters;
96 import org.onap.policy.api.DictionaryParameters;
97 import org.onap.policy.api.DictionaryResponse;
98 import org.onap.policy.api.EventRequestParameters;
99 import org.onap.policy.api.ImportParameters;
100 import org.onap.policy.api.MetricsRequestParameters;
101 import org.onap.policy.api.MetricsResponse;
102 import org.onap.policy.api.NotificationHandler;
103 import org.onap.policy.api.NotificationScheme;
104 import org.onap.policy.api.PDPNotification;
105 import org.onap.policy.api.PolicyChangeResponse;
106 import org.onap.policy.api.PolicyClass;
107 import org.onap.policy.api.PolicyConfig;
108 import org.onap.policy.api.PolicyConfigException;
109 import org.onap.policy.api.PolicyConfigType;
110 import org.onap.policy.api.PolicyDecisionException;
111 import org.onap.policy.api.PolicyEngineException;
112 import org.onap.policy.api.PolicyEventException;
113 import org.onap.policy.api.PolicyException;
114 import org.onap.policy.api.PolicyParameters;
115 import org.onap.policy.api.PolicyResponse;
116 import org.onap.policy.api.PolicyType;
117 import org.onap.policy.api.PushPolicyParameters;
118 import org.onap.policy.common.logging.flexlogger.FlexLogger;
119 import org.onap.policy.common.logging.flexlogger.Logger;
120 import org.onap.policy.models.APIDictionaryResponse;
121 import org.onap.policy.models.APIPolicyConfigResponse;
122 import org.onap.policy.std.utils.PolicyCommonConfigConstants;
123 import org.onap.policy.utils.AAFEnvironment;
124 import org.onap.policy.utils.PolicyUtils;
125 import org.onap.policy.xacml.api.XACMLErrorConstants;
126 import org.springframework.core.io.FileSystemResource;
127 import org.springframework.http.HttpEntity;
128 import org.springframework.http.HttpHeaders;
129 import org.springframework.http.HttpMethod;
130 import org.springframework.http.HttpStatus;
131 import org.springframework.http.MediaType;
132 import org.springframework.http.ResponseEntity;
133 import org.springframework.util.LinkedMultiValueMap;
134 import org.springframework.web.client.HttpClientErrorException;
135 import org.springframework.web.client.RestTemplate;
136 import org.xml.sax.InputSource;
137 import com.fasterxml.jackson.core.JsonProcessingException;
138 import com.google.gson.Gson;
139 import com.google.gson.GsonBuilder;
142 * PolicyEngine Implementation class
146 public class StdPolicyEngine {
148 private static String clientEncoding = null;
149 private String contentType = null;
150 private static List<String> pdps = null;
151 private static String environment = null;
152 private static String userName = null;
153 private static String pass = null;
154 private static List<String> encoding = null;
155 private static boolean junit = false;
156 private List<String> notificationType = new ArrayList<>();
157 private List<String> notificationURLList = new ArrayList<>();
158 private NotificationScheme scheme = null;
159 private NotificationHandler handler = null;
160 private AutoClientUEB uebClientThread = null;
161 private Thread registerUEBThread = null;
162 private boolean uebThread = false;
163 private AutoClientDMAAP dmaapClientThread = null;
164 private Thread registerDMAAPThread = null;
165 private boolean dmaapThread = false;
166 private String topic = null;
167 private String apiKey = null;
168 private String apiSecret = null;
170 private static final String UNIQUEID = UUID.randomUUID().toString();
171 private static final Logger LOGGER = FlexLogger.getLogger(StdPolicyConfig.class.getName());
174 * Taking the Property file even if it null.
176 public StdPolicyEngine(final String propertyFilePath, final String clientKey) throws PolicyEngineException {
177 setProperty(propertyFilePath, clientKey);
181 * Taking the Property structure even if it null.
183 public StdPolicyEngine(final Properties properties, final String clientKey) throws PolicyEngineException {
184 setProperty(properties, clientKey);
188 * Taking the Notification Constructor.
190 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme,
191 final NotificationHandler handler) throws PolicyEngineException {
192 setProperty(propertyFilePath, null);
193 this.scheme = scheme;
194 this.handler = handler;
195 if ((!UEB.equals(notificationType.get(0))) || (!DMAAP.equals(notificationType.get(0)))) {
196 AutoClientEnd.setAuto(scheme, handler);
198 notification(scheme, handler);
202 * Taking the Notification Constructor.
204 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme)
205 throws PolicyEngineException {
206 setProperty(propertyFilePath, null);
207 this.scheme = scheme;
212 * sendEvent API Implementation
214 public Collection<PolicyResponse> sendEvent(final Map<String, String> eventAttributes, final UUID requestID)
215 throws PolicyEventException {
216 return sendEventImpl(eventAttributes, requestID);
220 * sendEvent API Implementation for eventRequestParameters
222 public Collection<PolicyResponse> sendEvent(final EventRequestParameters eventRequestParameters)
223 throws PolicyEventException {
224 if (eventRequestParameters == null) {
225 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. ";
226 LOGGER.error(message);
227 throw new PolicyEventException(message);
229 return sendEventImpl(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID());
233 * getConfig using configRequestParameters Implementation
235 public Collection<PolicyConfig> getConfig(final ConfigRequestParameters configRequestParameters)
236 throws PolicyConfigException {
237 return getConfigImpl(configRequestParameters);
241 * listPolicies using configRequestParameters Implementation
243 public Collection<String> listConfig(final ConfigRequestParameters listPolicyRequestParameters)
244 throws PolicyConfigException {
245 return listConfigImpl(listPolicyRequestParameters);
249 * getDecision using the decision Attributes.
251 public DecisionResponse getDecision(final String onapName, final Map<String, String> decisionAttributes,
252 final UUID requestID) throws PolicyDecisionException {
253 return getDecisionImpl(onapName, decisionAttributes, requestID);
257 * getDecision Using decisionRequestParameters.
259 public DecisionResponse getDecision(final DecisionRequestParameters decisionRequestParameters)
260 throws PolicyDecisionException {
261 if (decisionRequestParameters == null) {
262 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. ";
263 LOGGER.error(message);
264 throw new PolicyDecisionException(message);
266 return getDecisionImpl(decisionRequestParameters.getOnapName(),
267 decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID());
271 * getMetrics using metricsRequestParameters
273 public MetricsResponse getMetrics(final MetricsRequestParameters parameters) throws PolicyException {
274 return getMetricsImpl(parameters);
277 public MetricsResponse getMetricsImpl(final MetricsRequestParameters parameters) throws PolicyException {
279 // Create the Request
281 if (parameters != null) {
282 body = PolicyUtils.objectToJsonString(parameters);
284 } catch (final JsonProcessingException jsonProcessingException) {
285 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
286 LOGGER.error(message);
287 throw new PolicyException(message, jsonProcessingException);
290 final StdMetricsResponse response = new StdMetricsResponse();
293 final ResponseEntity<String> result =
294 callNewPDP(GET_METRICS_RESOURCE_NAME, HttpMethod.GET, body, String.class);
296 response.setResponseMessage(result.getBody());
297 response.setResponseCode(result.getStatusCode().value());
299 } catch (final PolicyException exception) {
300 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
301 LOGGER.error(exception);
302 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
303 response.setResponseCode(ex.getRawStatusCode());
304 response.setResponseMessage(exception.getMessage());
307 final String message =
308 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
309 LOGGER.error(message, exception);
310 throw new PolicyException(message, exception);
315 * PushPolicy using pushPolicyParameters.
317 public PolicyChangeResponse pushPolicy(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
318 return pushPolicyImpl(pushPolicyParameters);
321 public PolicyChangeResponse pushPolicyImpl(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
322 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
326 body = PolicyUtils.objectToJsonString(pushPolicyParameters);
327 } catch (final JsonProcessingException e) {
328 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
329 LOGGER.error(message);
330 throw new PolicyException(message, e);
334 final ResponseEntity<String> result =
335 callNewPDP(PUSH_POLICY_RESOURCE_NAME, HttpMethod.PUT, body, String.class);
337 response.setResponseMessage(result.getBody());
338 response.setResponseCode(result.getStatusCode().value());
340 } catch (final PolicyException exception) {
341 return processException(exception);
346 * Delete a Policy using deletePolicyParameters
348 public PolicyChangeResponse deletePolicy(final DeletePolicyParameters parameters) throws PolicyException {
349 return deletePolicyImpl(parameters);
352 private PolicyChangeResponse deletePolicyImpl(final DeletePolicyParameters parameters) throws PolicyException {
353 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
357 body = PolicyUtils.objectToJsonString(parameters);
358 } catch (final JsonProcessingException e) {
359 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
360 LOGGER.error(message);
361 throw new PolicyException(message, e);
365 final ResponseEntity<String> result =
366 callNewPDP(DELETE_POLICY_RESOURCE_NAME, HttpMethod.DELETE, body, String.class);
368 response.setResponseMessage(result.getBody());
369 response.setResponseCode(result.getStatusCode().value());
370 } catch (final PolicyException exception) {
371 return processException(exception);
377 * getDictionaryItem Using dictionaryParameters
379 public DictionaryResponse getDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
380 return getDictionaryItemImpl(parameters);
383 private DictionaryResponse getDictionaryItemImpl(final DictionaryParameters parameters) throws PolicyException {
384 final StdDictionaryResponse response = new StdDictionaryResponse();
388 body = PolicyUtils.objectToJsonString(parameters);
389 } catch (final JsonProcessingException e) {
390 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
391 LOGGER.error(message);
392 throw new PolicyException(message, e);
396 final ResponseEntity<APIDictionaryResponse> result =
397 callNewPDP(GET_DICTIONARY_ITEMS_RESOURCE_NAME, HttpMethod.POST, body, APIDictionaryResponse.class);
399 return dictionaryResult(result.getBody());
400 } catch (final Exception exception) {
401 if (exception.getCause().getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
402 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM
403 + GET_DICTIONARY_ITEMS_RESOURCE_NAME;
404 LOGGER.error(message);
405 response.setResponseMessage(message);
406 response.setResponseCode(HttpStatus.UNAUTHORIZED.value());
409 if (exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
410 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
411 response.setResponseMessage(message);
412 response.setResponseCode(HttpStatus.BAD_REQUEST.value());
415 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
416 LOGGER.error(message, exception);
417 response.setResponseMessage(message);
418 response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
423 @SuppressWarnings("unchecked")
424 private StdDictionaryResponse dictionaryResult(final APIDictionaryResponse body) {
425 final StdDictionaryResponse response = new StdDictionaryResponse();
426 response.setResponseCode(body.getResponseCode());
427 response.setResponseMessage(body.getResponseMessage());
428 response.setDictionaryData((Map<String, String>) body.getDictionaryData());
429 if (body.getDictionaryJson() != null) {
430 final Gson objGson = new GsonBuilder().create();
431 final String mapToJson = objGson.toJson(body.getDictionaryJson());
432 try (final JsonReader jsonReader = Json.createReader(new StringReader(mapToJson));) {
433 final JsonObject object = jsonReader.readObject();
434 response.setDictionaryJson(object);
441 * createDictinaryItem Using dictionaryParameters.
443 public PolicyChangeResponse createDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
444 return createUpdateDictionaryItemImpl(parameters, false);
448 * updateDictinaryItem Using dictionaryParameters.
450 public PolicyChangeResponse updateDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
451 return createUpdateDictionaryItemImpl(parameters, true);
454 private PolicyChangeResponse createUpdateDictionaryItemImpl(final DictionaryParameters parameters,
455 final boolean updateFlag) throws PolicyException {
457 final String resource = getDictionaryResouceName(updateFlag);
461 body = PolicyUtils.objectToJsonString(parameters);
462 } catch (final JsonProcessingException jsonProcessingException) {
463 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
464 LOGGER.error(message);
465 throw new PolicyException(message, jsonProcessingException);
469 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
470 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
472 response.setResponseMessage(result.getBody());
473 response.setResponseCode(result.getStatusCode().value());
475 } catch (final PolicyException exception) {
476 return processException(exception);
480 private String getDictionaryResouceName(final boolean updateFlag) {
481 return updateFlag ? UPDATE_DICTIONARY_ITEM_RESOURCE_NAME : CREATE_DICTIONARY_ITEM_RESOURCE_NAME;
485 * PolicyEngine Import
487 public PolicyChangeResponse policyEngineImport(final ImportParameters importParameters) throws PolicyException {
488 return policyEngineImportImpl(importParameters);
491 private PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters) throws PolicyException {
492 final LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
495 final String body = PolicyUtils.objectToJsonString(importParameters);
496 parameters.set("importParametersJson", body);
497 parameters.set("file", new FileSystemResource(importParameters.getFilePath()));
498 } catch (final Exception e) {
499 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
500 LOGGER.error(message);
501 throw new PolicyException(message, e);
503 contentType = MediaType.MULTIPART_FORM_DATA_VALUE;
506 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
507 final ResponseEntity<String> result =
508 callNewPDP(POLICY_ENGINE_IMPORT_RESOURCE_NAME, HttpMethod.POST, parameters, String.class);
510 response.setResponseMessage(result.getBody());
511 response.setResponseCode(result.getStatusCode().value());
513 } catch (final PolicyException exception) {
514 return processException(exception);
521 * createPolicy Using policyParameters.
523 public PolicyChangeResponse createPolicy(final PolicyParameters policyParameters) throws PolicyException {
524 return createUpdatePolicyImpl(policyParameters, false);
528 * updatePolicy using policyParameters.
530 public PolicyChangeResponse updatePolicy(final PolicyParameters policyParameters) throws PolicyException {
531 return createUpdatePolicyImpl(policyParameters, true);
534 private PolicyChangeResponse createUpdatePolicyImpl(final PolicyParameters policyParameters,
535 final boolean updateFlag) throws PolicyException {
536 final String resource = getPolicyResourceName(updateFlag);
540 body = PolicyUtils.objectToJsonString(policyParameters);
541 } catch (final JsonProcessingException e) {
542 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
543 LOGGER.error(message);
544 throw new PolicyException(message, e);
548 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
549 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
551 response.setResponseMessage(result.getBody());
552 response.setResponseCode(result.getStatusCode().value());
554 } catch (final PolicyException exception) {
555 return processException(exception);
559 private String getPolicyResourceName(final boolean updateFlag) {
560 return updateFlag ? UPDATE_POLICY_RESOURCE_NAME : CREATE_POLICY_RESOURCE_NAME;
563 private PolicyChangeResponse processException(final PolicyException exception) throws PolicyException {
564 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
565 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
566 LOGGER.error(exception);
567 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
568 response.setResponseCode(ex.getRawStatusCode());
569 response.setResponseMessage(exception.getMessage());
572 final String message =
573 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
574 LOGGER.error(message, exception);
575 throw new PolicyException(message, exception);
579 private DecisionResponse getDecisionImpl(final String onapName, final Map<String, String> decisionAttributes,
580 final UUID requestID) throws PolicyDecisionException {
584 final DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters();
585 decisionRequestParameters.setDecisionAttributes(decisionAttributes);
586 decisionRequestParameters.setOnapName(onapName);
587 decisionRequestParameters.setRequestID(requestID);
588 body = PolicyUtils.objectToJsonString(decisionRequestParameters);
589 } catch (final JsonProcessingException e) {
590 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
591 LOGGER.error(message);
592 throw new PolicyDecisionException(message, e);
596 final ResponseEntity<StdDecisionResponse> result =
597 callNewPDP(GET_DECISION_RESOURCE_NAME, HttpMethod.POST, body, StdDecisionResponse.class);
599 return result.getBody();
600 } catch (final Exception exception) {
601 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
602 final String message = getErrorMessage(exception, defaulMessage, GET_DECISION_RESOURCE_NAME);
603 LOGGER.error(message, exception);
604 throw new PolicyDecisionException(message, exception);
608 private Collection<PolicyConfig> getConfigImpl(final ConfigRequestParameters configRequestParameters)
609 throws PolicyConfigException {
613 body = PolicyUtils.objectToJsonString(configRequestParameters);
614 } catch (final JsonProcessingException e) {
615 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
616 LOGGER.error(message);
617 throw new PolicyConfigException(message, e);
621 final ResponseEntity<APIPolicyConfigResponse[]> result =
622 callNewPDP(GET_CONFIG_RESOURCE_NAME, HttpMethod.POST, body, APIPolicyConfigResponse[].class);
624 return configResult(result.getBody());
625 } catch (final Exception exception) {
626 final String defaulMessage = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS + pdps;
627 final String message = getErrorMessage(exception, defaulMessage, GET_CONFIG_RESOURCE_NAME);
628 LOGGER.error(message, exception);
629 throw new PolicyConfigException(message, exception);
633 private ArrayList<PolicyConfig> configResult(final APIPolicyConfigResponse[] response)
634 throws PolicyConfigException {
635 final ArrayList<PolicyConfig> result = new ArrayList<>();
636 if (response == null) {
640 for (final APIPolicyConfigResponse policyConfigResponse : response) {
641 final StdPolicyConfig policyConfig = new StdPolicyConfig();
642 policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage());
643 policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions());
644 policyConfig.setPolicyConfigStatus(policyConfigResponse.getPolicyConfigStatus());
645 policyConfig.setPolicyName(policyConfigResponse.getPolicyName());
646 policyConfig.setPolicyType(policyConfigResponse.getType());
647 policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion());
648 policyConfig.setPolicyType(policyConfigResponse.getPolicyType());
649 policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes());
650 setMatches(policyConfig.getMatchingConditions());
651 if (policyConfigResponse.getType() != null) {
653 switch (policyConfigResponse.getType()) {
655 final StringReader reader = new StringReader(policyConfigResponse.getConfig());
656 try (final JsonReader jsonReader = Json.createReader(reader)) {
657 final JsonObject object = jsonReader.readObject();
658 policyConfig.setJsonObject(object);
662 policyConfig.setOther(policyConfigResponse.getConfig());
665 final Properties props = new Properties();
666 props.putAll(policyConfigResponse.getProperty());
667 policyConfig.setProperties(props);
670 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
671 final DocumentBuilder builder = factory.newDocumentBuilder();
672 final StringReader stringReader = new StringReader(policyConfigResponse.getConfig());
673 policyConfig.setDocument(builder.parse(new InputSource(stringReader)));
676 } catch (final Exception exception) {
677 LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + exception);
678 throw new PolicyConfigException(
679 XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", exception);
682 result.add(policyConfig);
687 private void setMatches(final Map<String, String> matchingConditions) {
688 final Matches match = new Matches();
689 final HashMap<String, String> configAttributes = new HashMap<>();
691 for (final Map.Entry<String, String> entry : matchingConditions.entrySet()) {
692 if (PolicyCommonConfigConstants.ONAP_NAME.equalsIgnoreCase(entry.getKey())) {
693 match.setOnapName(entry.getValue());
694 } else if (PolicyCommonConfigConstants.CONFIG_NAME.equalsIgnoreCase(entry.getKey())) {
695 match.setConfigName(entry.getValue());
697 configAttributes.put(entry.getKey(), entry.getValue());
700 if (!configAttributes.isEmpty()) {
701 match.setConfigAttributes(configAttributes);
703 MatchStore.storeMatch(match);
704 } catch (final Exception e) {
705 LOGGER.error("StoreMatch failed for Onap:" + match.getOnapName() + " Config: " + match.getConfigName(), e);
710 * Generic Rest Client to call PDP services.
712 <T> ResponseEntity<T> callNewPDP(final String resource, final HttpMethod method, final Object body,
713 final Class<T> responseType) throws PolicyException {
714 final RestTemplate restTemplate = new RestTemplate();
715 final HttpEntity<?> requestEntity = new HttpEntity<>(body, getHeaders());
716 ResponseEntity<T> result = null;
717 HttpClientErrorException exception = null;
719 while (pdpsCount < pdps.size()) {
721 result = restTemplate.exchange(pdps.get(0) + "/api/" + resource, method, requestEntity, responseType);
722 } catch (final HttpClientErrorException e) {
723 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
725 } catch (final Exception e) {
726 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
727 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
729 if (result == null) {
730 Collections.rotate(pdps, -1);
731 Collections.rotate(encoding, -1);
737 if (exception == null || exception.getStatusCode() == null) {
741 final String message = getHttpErrorMessage(exception, resource);
742 LOGGER.error(message);
743 throw new PolicyException(message, exception);
746 private String getHttpErrorMessage(final HttpClientErrorException exception, final String resource) {
747 if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
748 return XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + ERROR_AUTH_GET_PERM
751 if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
752 return XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":"
753 + exception.getResponseBodyAsString();
755 if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
756 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps + exception;
758 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":"
759 + exception.getResponseBodyAsString();
762 private HttpHeaders getHeaders() {
763 final HttpHeaders headers = new HttpHeaders();
764 headers.set("ClientAuth", "Basic " + clientEncoding);
765 headers.set("Authorization", "Basic " + encoding.get(0));
766 if (contentType != null) {
767 headers.set("Content-Type", contentType);
769 headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
771 headers.set("Environment", environment);
775 private static void setClientEncoding() {
776 final Base64.Encoder encoder = Base64.getEncoder();
777 clientEncoding = encoder.encodeToString((userName + ":" + pass).getBytes(StandardCharsets.UTF_8));
780 private Collection<String> listConfigImpl(final ConfigRequestParameters listRequestParameters)
781 throws PolicyConfigException {
782 final Collection<String> policyList = new ArrayList<>();
784 policyList.add(TEST_POLICY_NAME);
787 final Collection<PolicyConfig> policyConfig = getConfigImpl(listRequestParameters);
788 for (final PolicyConfig policy : policyConfig) {
789 if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains(PE300)) {
790 policyList.add(policy.getPolicyConfigMessage());
792 policyList.add("Policy Name: " + policy.getPolicyName());
798 private Collection<PolicyResponse> sendEventImpl(final Map<String, String> eventAttributes, final UUID requestID)
799 throws PolicyEventException {
803 // Long way here, can be shortened and will be done.
804 final EventRequestParameters eventRequestParameters = new EventRequestParameters();
805 eventRequestParameters.setEventAttributes(eventAttributes);
806 eventRequestParameters.setRequestID(requestID);
807 body = PolicyUtils.objectToJsonString(eventRequestParameters);
808 } catch (final JsonProcessingException e) {
809 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
810 LOGGER.error(message);
811 throw new PolicyEventException(message, e);
815 final ResponseEntity<StdPolicyResponse[]> result =
816 callNewPDP(SEND_EVENT_RESOURCE_NAME, HttpMethod.POST, body, StdPolicyResponse[].class);
818 return eventResult(result.getBody());
819 } catch (final Exception exception) {
820 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
821 final String message = getErrorMessage(exception, defaulMessage, SEND_EVENT_RESOURCE_NAME);
822 LOGGER.error(message, exception);
823 throw new PolicyEventException(message, exception);
827 private String getErrorMessage(final Exception exception, final String defaulMessage, final String resource) {
828 final Throwable cause = exception.getCause();
829 if (cause != null && cause.getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
830 return XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource;
832 if (cause != null && exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
833 return XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
835 return defaulMessage;
838 private ArrayList<PolicyResponse> eventResult(final StdPolicyResponse[] response) {
839 final ArrayList<PolicyResponse> eventResult = new ArrayList<>();
840 if (response != null && response.length > 0) {
841 for (final StdPolicyResponse policyConfigResponse : response) {
842 eventResult.add(policyConfigResponse);
848 private void setProperty(final String propertyFilePath, String clientKey) throws PolicyEngineException {
849 if (propertyFilePath == null) {
850 throw new PolicyEngineException(
851 XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided");
853 final Properties prop = getProperties(propertyFilePath);
854 setProperty(prop,clientKey);
857 private void setProperty(final Properties properties, String clientKey) throws PolicyEngineException {
858 if (properties == null) {
859 throw new PolicyEngineException(
860 XACMLErrorConstants.ERROR_DATA_ISSUE + "NO properties provided, the value is NULL");
863 // UEB and DMAAP Settings
864 final String notificationTypeValue = properties.getProperty(NOTIFICATION_TYPE_PROP_NAME);
865 final String serverList = properties.getProperty(NOTIFICATION_SERVERS_PROP_NAME);
866 topic = properties.getProperty(NOTIFICATION_TOPIC_PROP_NAME);
867 apiKey = properties.getProperty(UEB_API_KEY_PROP_NAME);
868 apiSecret = properties.getProperty(UEB_API_SECRET_PROP_NAME);
870 setNotificationType(notificationTypeValue);
872 if (serverList == null) {
873 notificationType.clear();
874 notificationType.add(DEFAULT_NOTIFICATION);
876 "Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets");
878 notificationURLList = getPropertyValueAsList(serverList.trim());
882 topic = topic.trim();
884 LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter.");
887 // Client ID Authorization Settings.
888 final String clientID = properties.getProperty(CLIENT_ID_PROP_NAME);
889 if (clientKey == null) {
890 clientKey = getClientKeyFromProperties(properties);
892 if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) {
893 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
894 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
895 throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS
896 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
898 setClientId(clientID.trim());
899 setClientKey(clientKey.trim());
901 setEnvironment(properties);
902 // Initializing the values.
904 readPdpProperites(properties);
905 // Get JUNIT property from properties file when running tests
906 checkJunit(properties);
909 private void readPdpProperites(final Properties prop) throws PolicyEngineException {
910 // Check the Keys for PDP_URLs
911 for (final String propertyKey : prop.stringPropertyNames()) {
912 if (propertyKey.startsWith(PDP_URL_PROP_NAME)) {
913 readPDPPropertyURL(prop, propertyKey);
916 if (pdps == null || pdps.isEmpty()) {
917 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
918 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
922 private void readPDPPropertyURL(Properties prop, String propertyKey) throws PolicyEngineException {
923 final String propertyValue = prop.getProperty(propertyKey);
924 if (propertyValue == null) {
925 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
926 + "Properties file doesn't have the PDP_URL parameter");
928 if (propertyValue.contains(SEMICOLLON)) {
929 final List<String> pdpDefault = Arrays.asList(propertyValue.split(REGEX));
930 for (final String pdpVal : pdpDefault) {
931 readPDPParam(pdpVal);
934 readPDPParam(propertyValue);
938 private void setNotificationType(final String propertyValue) {
939 if (propertyValue == null) {
940 notificationType.add(DEFAULT_NOTIFICATION);
942 "Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets");
944 notificationType = getPropertyValueAsList(propertyValue.trim());
948 private String getClientKeyFromProperties(final Properties prop) {
949 final String clientKeyValue = prop.getProperty(CLIENT_KEY_PROP_NAME);
951 return PolicyUtils.decode(clientKeyValue);
952 } catch (UnsupportedEncodingException | IllegalArgumentException e) {
953 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
954 + " Cannot Decode the given Password Proceeding with given Password!!", e);
956 return clientKeyValue;
959 private Properties getProperties(final String propertyFilePath) throws PolicyEngineException {
960 // Adding logic for remote Properties file.
961 if (propertyFilePath.startsWith(HTTP)) {
962 return getRemoteProperties(propertyFilePath);
964 return getFileProperties(propertyFilePath);
967 private Properties getFileProperties(final String propertyFilePath) throws PolicyEngineException {
968 final Path file = Paths.get(propertyFilePath);
969 if (!file.toFile().exists()) {
970 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
971 + "File doesn't exist in the specified Path " + file.toString());
973 if (file.toString().endsWith(".properties")) {
974 try (BufferedReader bufferedReader = Files.newBufferedReader(file);) {
975 final Properties prop = new Properties();
976 prop.load(bufferedReader);
978 } catch (final IOException exception) {
979 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + exception);
980 throw new PolicyEngineException(
981 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", exception);
984 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath);
985 throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file");
988 private Properties getRemoteProperties(final String propertyFilePath) throws PolicyEngineException {
990 final URL configURL = new URL(propertyFilePath);
991 final URLConnection connection = configURL.openConnection();
992 final Properties prop = new Properties();
993 prop.load(connection.getInputStream());
995 } catch (final IOException e) {
996 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
997 throw new PolicyEngineException(
998 XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage());
1002 private List<String> getPropertyValueAsList(final String propertyValue) {
1003 if (propertyValue.contains(COMMA)) {
1004 return Arrays.asList(propertyValue.split(COMMA));
1006 final List<String> valuesList = new ArrayList<>();
1007 valuesList.add(propertyValue);
1011 private static void checkJunit(final Properties prop) {
1012 final String junitFlag = prop.getProperty(JUNIT_PROP_NAME);
1013 if (junitFlag == null || junitFlag.isEmpty()) {
1014 LOGGER.info("No JUNIT property provided, this will not be executed as a test.");
1016 if ("test".equalsIgnoreCase(junitFlag)) {
1017 StdPolicyEngine.junit = true;
1019 StdPolicyEngine.junit = false;
1024 private static void init() {
1025 pdps = new ArrayList<>();
1026 encoding = new ArrayList<>();
1029 private static void setEnvironment(final Properties prop) {
1030 environment = prop.getProperty(ENVIRONMENT_PROP_NAME, AAFEnvironment.DEVL.toString());
1031 if (environment.equalsIgnoreCase(AAFEnvironment.TEST.toString())) {
1032 environment = AAFEnvironment.TEST.toString();
1033 } else if (environment.equalsIgnoreCase(AAFEnvironment.PROD.toString())) {
1034 environment = AAFEnvironment.PROD.toString();
1036 environment = AAFEnvironment.DEVL.toString();
1040 private static void setClientId(final String clientID) {
1041 userName = clientID;
1045 * Read the PDP_URL parameter
1047 private void readPDPParam(final String pdpVal) throws PolicyEngineException {
1048 if (pdpVal.contains(COMMA)) {
1049 final List<String> pdpValues = Arrays.asList(pdpVal.split(PDP_VALUE_REGEX));
1050 if (pdpValues.size() == 3) {
1052 pdps.add(pdpValues.get(0));
1053 // 1:2 will be UserID:Password
1054 final String userID = pdpValues.get(1);
1055 final String userPas = pdpValues.get(2);
1056 final Base64.Encoder encoder = Base64.getEncoder();
1057 encoding.add(encoder.encodeToString((userID + ":" + userPas).getBytes(StandardCharsets.UTF_8)));
1059 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues);
1060 throw new PolicyEngineException(
1061 XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues);
1065 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal);
1066 throw new PolicyEngineException(
1067 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values.");
1072 * Allowing changes to the scheme and Handler.
1074 public void notification(final NotificationScheme scheme, final NotificationHandler handler) {
1075 this.scheme = scheme;
1076 this.handler = handler;
1077 LOGGER.debug("Scheme is : " + scheme.toString());
1078 LOGGER.debug("Handler is : " + handler.getClass().getName());
1080 if (UEB.equals(notificationType.get(0))) {
1081 if (this.uebThread) {
1082 AutoClientUEB.setAuto(scheme, handler);
1083 this.uebThread = registerUEBThread.isAlive();
1085 } else if (notificationType.get(0).equals(DMAAP)) {
1086 if (this.dmaapThread) {
1087 AutoClientDMAAP.setAuto(scheme, handler);
1088 this.dmaapThread = registerDMAAPThread.isAlive();
1091 AutoClientEnd.setAuto(scheme, handler);
1101 if (UEB.equals(notificationType.get(0)) && !this.uebThread) {
1102 this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret);
1103 AutoClientUEB.setAuto(scheme, handler);
1104 this.registerUEBThread = new Thread(this.uebClientThread);
1105 this.registerUEBThread.start();
1106 this.uebThread = true;
1107 } else if (notificationType.get(0).equals(DMAAP) && !this.dmaapThread) {
1108 this.dmaapClientThread = new AutoClientDMAAP(notificationURLList, topic, userName, pass);
1109 AutoClientDMAAP.setAuto(scheme, handler);
1110 this.registerDMAAPThread = new Thread(this.dmaapClientThread);
1111 this.registerDMAAPThread.start();
1112 this.dmaapThread = true;
1114 if (pdps.get(0) != null) {
1115 if (AutoClientEnd.getUrl() == null) {
1116 AutoClientEnd.start(pdps.get(0));
1118 AutoClientEnd.stop();
1119 AutoClientEnd.start(pdps.get(0));
1126 * Gets the Notification if one exists. Used only for Manual Polling purposes.
1128 public PDPNotification getNotification() {
1129 // Check if there is proper scheme..
1130 PDPNotification notification;
1131 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)
1132 || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
1133 if (UEB.equals(notificationType.get(0))) {
1134 ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID);
1135 notification = ManualClientEndUEB.result(scheme);
1136 } else if (notificationType.get(0).equals(DMAAP)) {
1137 ManualClientEndDMAAP.start(notificationURLList, topic, UNIQUEID, userName, pass);
1138 notification = ManualClientEndDMAAP.result(scheme);
1140 ManualClientEnd.start(pdps.get(0));
1141 LOGGER.debug("manual notification requested.. : " + scheme.toString());
1142 notification = ManualClientEnd.result(scheme);
1144 if (notification == null) {
1145 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet..");
1148 return notification;
1154 * Setting the Scheme.
1156 public void setScheme(final NotificationScheme scheme) {
1157 this.scheme = scheme;
1158 if (UEB.equals(notificationType.get(0))) {
1159 AutoClientUEB.setScheme(this.scheme);
1160 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1161 ManualClientEndUEB.createTopic(pdps.get(0), UNIQUEID, notificationURLList);
1163 } else if (notificationType.get(0).equals(DMAAP)) {
1164 AutoClientDMAAP.setScheme(this.scheme);
1165 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1166 ManualClientEndDMAAP.createTopic(topic, UNIQUEID, notificationURLList, userName, pass);
1169 AutoClientEnd.setScheme(this.scheme);
1174 * Returns the Scheme
1176 public NotificationScheme getScheme() {
1181 * Returns the NotificationHandler
1183 public NotificationHandler getNotificationHandler() {
1184 return this.handler;
1188 * Stop the Notification Service if its running.
1190 public void stopNotification() {
1191 if (this.scheme != null && this.handler != null
1192 && (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)
1193 || this.scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS))) {
1194 LOGGER.info("Clear Notification called.. ");
1195 if (UEB.equals(notificationType.get(0))) {
1196 this.uebClientThread.terminate();
1197 this.uebThread = false;
1198 } else if (notificationType.get(0).equals(DMAAP)) {
1199 this.dmaapClientThread.terminate();
1200 this.dmaapThread = false;
1202 AutoClientEnd.stop();
1208 * Push a policy to the PDP API implementation
1210 public String pushPolicy(final String policyScope, final String policyName, final String policyType,
1211 final String pdpGroup, final UUID requestID) throws PolicyException {
1212 validateParameters(policyName, policyScope);
1214 final PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
1215 pushPolicyParameters.setPolicyName(policyScope + "." + policyName);
1216 pushPolicyParameters.setPolicyType(policyType);
1217 pushPolicyParameters.setPdpGroup(pdpGroup);
1218 pushPolicyParameters.setRequestID(requestID);
1219 return pushPolicyImpl(pushPolicyParameters).getResponseMessage();
1222 private boolean isNotValid(final String value) {
1223 return value == null || value.trim().isEmpty();
1226 public String createUpdateConfigPolicy(final String policyName, final String policyDescription,
1227 final String onapName, final String configName, final Map<String, String> configAttributes,
1228 final String configType, final String body, final String policyScope, final UUID requestID,
1229 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1230 final boolean updateFlag) throws PolicyException {
1231 return createUpdateConfigPolicyImpl(policyName, policyDescription, onapName, configName, configAttributes,
1232 configType, body, policyScope, requestID, riskLevel, riskType, guard, ttlDate, updateFlag);
1236 * Create Config Policy API Implementation
1238 private String createUpdateConfigPolicyImpl(final String policyName, final String policyDescription,
1239 final String onapName, final String configName, final Map<String, String> configAttributes,
1240 final String configType, final String body, final String policyScope, final UUID requestID,
1241 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1242 final boolean updateFlag) throws PolicyException {
1244 validateParameters(policyName, policyScope);
1246 final PolicyParameters policyParameters = new PolicyParameters();
1247 policyParameters.setPolicyClass(PolicyClass.Config);
1248 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
1249 policyParameters.setPolicyName(policyScope + "." + policyName);
1250 policyParameters.setPolicyDescription(policyDescription);
1251 policyParameters.setOnapName(onapName);
1252 policyParameters.setConfigName(configName);
1254 final Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
1255 attributes.put(AttributeType.MATCHING, configAttributes);
1257 policyParameters.setAttributes(attributes);
1258 policyParameters.setConfigBodyType(PolicyType.valueOf(configType));
1259 policyParameters.setConfigBody(body);
1260 policyParameters.setRequestID(requestID);
1261 policyParameters.setRiskLevel(riskLevel);
1262 policyParameters.setRiskType(riskType);
1263 policyParameters.setGuard(Boolean.parseBoolean(guard));
1264 policyParameters.setTtlDate(toDate(ttlDate));
1265 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1268 private Date toDate(final String dateString) {
1270 return new SimpleDateFormat(DATE_FORMAT).parse(dateString);
1271 } catch (final ParseException e) {
1272 LOGGER.warn("Error Parsing date given " + dateString);
1277 public String createUpdateConfigFirewallPolicy(final String policyName, final JsonObject firewallJson,
1278 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1279 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1280 return createUpdateConfigFirewallPolicyImpl(policyName, firewallJson, policyScope, requestID, riskLevel,
1281 riskType, guard, ttlDate, updateFlag);
1285 * Create Update Config Firewall Policy API implementation
1287 private String createUpdateConfigFirewallPolicyImpl(final String policyName, final JsonObject firewallJson,
1288 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1289 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1290 validateParameters(policyName, policyScope);
1292 final PolicyParameters policyParameters = new PolicyParameters();
1293 policyParameters.setPolicyClass(PolicyClass.Config);
1294 policyParameters.setPolicyConfigType(PolicyConfigType.Firewall);
1295 policyParameters.setPolicyName(policyScope + "." + policyName);
1296 policyParameters.setConfigBody(firewallJson.toString());
1297 policyParameters.setRequestID(requestID);
1298 policyParameters.setRiskLevel(riskLevel);
1299 policyParameters.setRiskType(riskType);
1300 policyParameters.setGuard(Boolean.parseBoolean(guard));
1301 policyParameters.setTtlDate(toDate(ttlDate));
1302 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1305 private void validateParameters(final String policyName, final String policyScope) throws PolicyException {
1306 if (isNotValid(policyScope)) {
1307 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
1308 LOGGER.error(message);
1309 throw new PolicyException(message);
1311 if (isNotValid(policyName)) {
1312 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
1313 LOGGER.error(message);
1314 throw new PolicyException(message);
1318 public static void setClientKey(final String clientKey) {
1319 if (clientKey != null && !clientKey.isEmpty()) {
1320 StdPolicyEngine.pass = clientKey;
1321 setClientEncoding();
1326 * Get the Environment.
1328 public static String getEnvironment() {
1333 * Rotate the PDP list upon WEBsocket Failures
1335 public static void rotatePDPList() {
1336 Collections.rotate(pdps, -1);
1337 Collections.rotate(encoding, -1);
1341 * Get the latest PDP
1343 public static String getPDPURL() {
1353 List<String> getNotificationType() {
1354 return notificationType;
1358 List<String> getNotificationURLList() {
1359 return notificationURLList;