2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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 com.fasterxml.jackson.core.JsonProcessingException;
64 import com.google.gson.Gson;
65 import com.google.gson.GsonBuilder;
66 import java.io.BufferedReader;
67 import java.io.IOException;
68 import java.io.StringReader;
69 import java.io.UnsupportedEncodingException;
71 import java.net.URLConnection;
72 import java.nio.charset.StandardCharsets;
73 import java.nio.file.Files;
74 import java.nio.file.Path;
75 import java.nio.file.Paths;
76 import java.text.ParseException;
77 import java.text.SimpleDateFormat;
78 import java.util.ArrayList;
79 import java.util.Arrays;
80 import java.util.Base64;
81 import java.util.Collection;
82 import java.util.Collections;
83 import java.util.Date;
84 import java.util.HashMap;
85 import java.util.List;
87 import java.util.Properties;
88 import java.util.UUID;
89 import javax.json.Json;
90 import javax.json.JsonObject;
91 import javax.json.JsonReader;
92 import javax.xml.parsers.DocumentBuilder;
93 import javax.xml.parsers.DocumentBuilderFactory;
94 import org.onap.policy.api.AttributeType;
95 import org.onap.policy.api.ConfigNameRequest;
96 import org.onap.policy.api.ConfigRequestParameters;
97 import org.onap.policy.api.DecisionRequestParameters;
98 import org.onap.policy.api.DecisionResponse;
99 import org.onap.policy.api.DeletePolicyParameters;
100 import org.onap.policy.api.DictionaryParameters;
101 import org.onap.policy.api.DictionaryResponse;
102 import org.onap.policy.api.EventRequestParameters;
103 import org.onap.policy.api.ImportParameters;
104 import org.onap.policy.api.MetricsRequestParameters;
105 import org.onap.policy.api.MetricsResponse;
106 import org.onap.policy.api.NotificationHandler;
107 import org.onap.policy.api.NotificationScheme;
108 import org.onap.policy.api.PDPNotification;
109 import org.onap.policy.api.PolicyChangeResponse;
110 import org.onap.policy.api.PolicyClass;
111 import org.onap.policy.api.PolicyConfig;
112 import org.onap.policy.api.PolicyConfigException;
113 import org.onap.policy.api.PolicyConfigType;
114 import org.onap.policy.api.PolicyDecisionException;
115 import org.onap.policy.api.PolicyEngineException;
116 import org.onap.policy.api.PolicyEventException;
117 import org.onap.policy.api.PolicyException;
118 import org.onap.policy.api.PolicyParameters;
119 import org.onap.policy.api.PolicyResponse;
120 import org.onap.policy.api.PolicyType;
121 import org.onap.policy.api.PushPolicyParameters;
122 import org.onap.policy.common.logging.flexlogger.FlexLogger;
123 import org.onap.policy.common.logging.flexlogger.Logger;
124 import org.onap.policy.models.APIDictionaryResponse;
125 import org.onap.policy.models.APIPolicyConfigResponse;
126 import org.onap.policy.std.utils.PolicyCommonConfigConstants;
127 import org.onap.policy.utils.AAFEnvironment;
128 import org.onap.policy.utils.PolicyUtils;
129 import org.onap.policy.xacml.api.XACMLErrorConstants;
130 import org.springframework.core.io.FileSystemResource;
131 import org.springframework.http.HttpEntity;
132 import org.springframework.http.HttpHeaders;
133 import org.springframework.http.HttpMethod;
134 import org.springframework.http.HttpStatus;
135 import org.springframework.http.MediaType;
136 import org.springframework.http.ResponseEntity;
137 import org.springframework.util.LinkedMultiValueMap;
138 import org.springframework.web.client.HttpClientErrorException;
139 import org.springframework.web.client.RestTemplate;
140 import org.xml.sax.InputSource;
143 * PolicyEngine Implementation class
147 public class StdPolicyEngine {
149 private static String clientEncoding = null;
150 private String contentType = null;
151 private static List<String> pdps = null;
152 private static String environment = null;
153 private static String userName = null;
154 private static String pass = null;
155 private static List<String> encoding = null;
156 private static boolean junit = false;
157 private List<String> notificationType = new ArrayList<>();
158 private List<String> notificationURLList = new ArrayList<>();
159 private NotificationScheme scheme = null;
160 private NotificationHandler handler = null;
161 private AutoClientUEB uebClientThread = null;
162 private Thread registerUEBThread = null;
163 private boolean uebThread = false;
164 private AutoClientDMAAP dmaapClientThread = null;
165 private Thread registerDMAAPThread = null;
166 private boolean dmaapThread = false;
167 private String topic = null;
168 private String apiKey = null;
169 private String apiSecret = null;
171 private static final String UNIQUEID = UUID.randomUUID().toString();
172 private static final Logger LOGGER = FlexLogger.getLogger(StdPolicyConfig.class.getName());
173 private static final String LIST_POLICY_RESOURCE_NAME = "listPolicy";
176 * Taking the Property file even if it null.
178 public StdPolicyEngine(final String propertyFilePath, final String clientKey) throws PolicyEngineException {
179 setProperty(propertyFilePath, clientKey);
183 * Taking the Property structure even if it null.
185 public StdPolicyEngine(final Properties properties, final String clientKey) throws PolicyEngineException {
186 setProperty(properties, clientKey);
190 * Taking the Notification Constructor.
192 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme,
193 final NotificationHandler handler) throws PolicyEngineException {
194 setProperty(propertyFilePath, null);
195 this.scheme = scheme;
196 this.handler = handler;
197 if ((!UEB.equals(notificationType.get(0))) || (!DMAAP.equals(notificationType.get(0)))) {
198 AutoClientEnd.setAuto(scheme, handler);
200 notification(scheme, handler);
204 * Taking the Notification Constructor.
206 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme)
207 throws PolicyEngineException {
208 setProperty(propertyFilePath, null);
209 this.scheme = scheme;
214 * sendEvent API Implementation
216 public Collection<PolicyResponse> sendEvent(final Map<String, String> eventAttributes, final UUID requestID)
217 throws PolicyEventException {
218 return sendEventImpl(eventAttributes, requestID);
222 * sendEvent API Implementation for eventRequestParameters
224 public Collection<PolicyResponse> sendEvent(final EventRequestParameters eventRequestParameters)
225 throws PolicyEventException {
226 if (eventRequestParameters == null) {
227 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. ";
228 LOGGER.error(message);
229 throw new PolicyEventException(message);
231 return sendEventImpl(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID());
235 * getConfig using configRequestParameters Implementation
237 public Collection<PolicyConfig> getConfig(final ConfigRequestParameters configRequestParameters)
238 throws PolicyConfigException {
239 return getConfigImpl(configRequestParameters);
243 * listPolicies using configRequestParameters Implementation
245 public Collection<String> listConfig(final ConfigRequestParameters listPolicyRequestParameters)
246 throws PolicyConfigException {
247 return listConfigImpl(listPolicyRequestParameters);
251 * listPolicies from PDP using ConfigNameRequest Implementation
253 public Collection<String> listPolicy(final ConfigNameRequest listPolicyRequestParameters)
254 throws PolicyConfigException {
255 return listPolicyImpl(listPolicyRequestParameters);
259 * getDecision using the decision Attributes.
261 public DecisionResponse getDecision(final String onapName, final Map<String, String> decisionAttributes,
262 final UUID requestID) throws PolicyDecisionException {
263 return getDecisionImpl(onapName, decisionAttributes, requestID);
267 * getDecision Using decisionRequestParameters.
269 public DecisionResponse getDecision(final DecisionRequestParameters decisionRequestParameters)
270 throws PolicyDecisionException {
271 if (decisionRequestParameters == null) {
272 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. ";
273 LOGGER.error(message);
274 throw new PolicyDecisionException(message);
276 return getDecisionImpl(decisionRequestParameters.getOnapName(),
277 decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID());
281 * getMetrics using metricsRequestParameters
283 public MetricsResponse getMetrics(final MetricsRequestParameters parameters) throws PolicyException {
284 return getMetricsImpl(parameters);
287 public MetricsResponse getMetricsImpl(final MetricsRequestParameters parameters) throws PolicyException {
289 // Create the Request
291 if (parameters != null) {
292 body = PolicyUtils.objectToJsonString(parameters);
294 } catch (final JsonProcessingException jsonProcessingException) {
295 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
296 LOGGER.error(message);
297 throw new PolicyException(message, jsonProcessingException);
300 final StdMetricsResponse response = new StdMetricsResponse();
303 final ResponseEntity<String> result =
304 callNewPDP(GET_METRICS_RESOURCE_NAME, HttpMethod.GET, body, String.class);
306 response.setResponseMessage(result.getBody());
307 response.setResponseCode(result.getStatusCode().value());
309 } catch (final PolicyException exception) {
310 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
311 LOGGER.error(exception);
312 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
313 response.setResponseCode(ex.getRawStatusCode());
314 response.setResponseMessage(exception.getMessage());
317 final String message =
318 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
319 LOGGER.error(message, exception);
320 throw new PolicyException(message, exception);
325 * PushPolicy using pushPolicyParameters.
327 public PolicyChangeResponse pushPolicy(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
328 return pushPolicyImpl(pushPolicyParameters);
331 public PolicyChangeResponse pushPolicyImpl(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
332 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
336 body = PolicyUtils.objectToJsonString(pushPolicyParameters);
337 } catch (final JsonProcessingException e) {
338 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
339 LOGGER.error(message);
340 throw new PolicyException(message, e);
344 final ResponseEntity<String> result =
345 callNewPDP(PUSH_POLICY_RESOURCE_NAME, HttpMethod.PUT, body, String.class);
347 response.setResponseMessage(result.getBody());
348 response.setResponseCode(result.getStatusCode().value());
350 } catch (final PolicyException exception) {
351 return processException(exception);
356 * Delete a Policy using deletePolicyParameters
358 public PolicyChangeResponse deletePolicy(final DeletePolicyParameters parameters) throws PolicyException {
359 return deletePolicyImpl(parameters);
362 private PolicyChangeResponse deletePolicyImpl(final DeletePolicyParameters parameters) throws PolicyException {
363 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
367 body = PolicyUtils.objectToJsonString(parameters);
368 } catch (final JsonProcessingException e) {
369 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
370 LOGGER.error(message);
371 throw new PolicyException(message, e);
375 final ResponseEntity<String> result =
376 callNewPDP(DELETE_POLICY_RESOURCE_NAME, HttpMethod.DELETE, body, String.class);
378 response.setResponseMessage(result.getBody());
379 response.setResponseCode(result.getStatusCode().value());
380 } catch (final PolicyException exception) {
381 return processException(exception);
387 * getDictionaryItem Using dictionaryParameters
389 public DictionaryResponse getDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
390 return getDictionaryItemImpl(parameters);
393 private DictionaryResponse getDictionaryItemImpl(final DictionaryParameters parameters) throws PolicyException {
394 final StdDictionaryResponse response = new StdDictionaryResponse();
398 body = PolicyUtils.objectToJsonString(parameters);
399 } catch (final JsonProcessingException e) {
400 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
401 LOGGER.error(message);
402 throw new PolicyException(message, e);
406 final ResponseEntity<APIDictionaryResponse> result =
407 callNewPDP(GET_DICTIONARY_ITEMS_RESOURCE_NAME, HttpMethod.POST, body, APIDictionaryResponse.class);
409 return dictionaryResult(result.getBody());
410 } catch (final Exception exception) {
411 if (exception.getCause().getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
412 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM
413 + GET_DICTIONARY_ITEMS_RESOURCE_NAME;
414 LOGGER.error(message);
415 response.setResponseMessage(message);
416 response.setResponseCode(HttpStatus.UNAUTHORIZED.value());
419 if (exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
420 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
421 response.setResponseMessage(message);
422 response.setResponseCode(HttpStatus.BAD_REQUEST.value());
425 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
426 LOGGER.error(message, exception);
427 response.setResponseMessage(message);
428 response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
433 @SuppressWarnings("unchecked")
434 private StdDictionaryResponse dictionaryResult(final APIDictionaryResponse body) {
435 final StdDictionaryResponse response = new StdDictionaryResponse();
436 response.setResponseCode(body.getResponseCode());
437 response.setResponseMessage(body.getResponseMessage());
438 response.setDictionaryData((Map<String, String>) body.getDictionaryData());
439 if (body.getDictionaryJson() != null) {
440 final Gson objGson = new GsonBuilder().create();
441 final String mapToJson = objGson.toJson(body.getDictionaryJson());
442 try (final JsonReader jsonReader = Json.createReader(new StringReader(mapToJson));) {
443 final JsonObject object = jsonReader.readObject();
444 response.setDictionaryJson(object);
451 * createDictinaryItem Using dictionaryParameters.
453 public PolicyChangeResponse createDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
454 return createUpdateDictionaryItemImpl(parameters, false);
458 * updateDictinaryItem Using dictionaryParameters.
460 public PolicyChangeResponse updateDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
461 return createUpdateDictionaryItemImpl(parameters, true);
464 private PolicyChangeResponse createUpdateDictionaryItemImpl(final DictionaryParameters parameters,
465 final boolean updateFlag) throws PolicyException {
467 final String resource = getDictionaryResouceName(updateFlag);
471 body = PolicyUtils.objectToJsonString(parameters);
472 } catch (final JsonProcessingException jsonProcessingException) {
473 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
474 LOGGER.error(message);
475 throw new PolicyException(message, jsonProcessingException);
479 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
480 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
482 response.setResponseMessage(result.getBody());
483 response.setResponseCode(result.getStatusCode().value());
485 } catch (final PolicyException exception) {
486 return processException(exception);
490 private String getDictionaryResouceName(final boolean updateFlag) {
491 return updateFlag ? UPDATE_DICTIONARY_ITEM_RESOURCE_NAME : CREATE_DICTIONARY_ITEM_RESOURCE_NAME;
495 * PolicyEngine Import
497 public PolicyChangeResponse policyEngineImport(final ImportParameters importParameters) throws PolicyException {
498 return policyEngineImportImpl(importParameters);
501 private PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters)
502 throws PolicyException {
503 final LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
506 final String body = PolicyUtils.objectToJsonString(importParameters);
507 parameters.set("importParametersJson", body);
508 parameters.set("file", new FileSystemResource(importParameters.getFilePath()));
509 } catch (final Exception e) {
510 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
511 LOGGER.error(message);
512 throw new PolicyException(message, e);
514 contentType = MediaType.MULTIPART_FORM_DATA_VALUE;
517 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
518 final ResponseEntity<String> result =
519 callNewPDP(POLICY_ENGINE_IMPORT_RESOURCE_NAME, HttpMethod.POST, parameters, String.class);
521 response.setResponseMessage(result.getBody());
522 response.setResponseCode(result.getStatusCode().value());
524 } catch (final PolicyException exception) {
525 return processException(exception);
532 * createPolicy Using policyParameters.
534 public PolicyChangeResponse createPolicy(final PolicyParameters policyParameters) throws PolicyException {
535 return createUpdatePolicyImpl(policyParameters, false);
539 * updatePolicy using policyParameters.
541 public PolicyChangeResponse updatePolicy(final PolicyParameters policyParameters) throws PolicyException {
542 return createUpdatePolicyImpl(policyParameters, true);
545 private PolicyChangeResponse createUpdatePolicyImpl(final PolicyParameters policyParameters,
546 final boolean updateFlag) throws PolicyException {
547 final String resource = getPolicyResourceName(updateFlag);
551 body = PolicyUtils.objectToJsonString(policyParameters);
552 } catch (final JsonProcessingException e) {
553 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
554 LOGGER.error(message);
555 throw new PolicyException(message, e);
559 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
560 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
562 response.setResponseMessage(result.getBody());
563 response.setResponseCode(result.getStatusCode().value());
565 } catch (final PolicyException exception) {
566 return processException(exception);
570 private String getPolicyResourceName(final boolean updateFlag) {
571 return updateFlag ? UPDATE_POLICY_RESOURCE_NAME : CREATE_POLICY_RESOURCE_NAME;
574 private PolicyChangeResponse processException(final PolicyException exception) throws PolicyException {
575 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
576 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
577 LOGGER.error(exception);
578 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
579 response.setResponseCode(ex.getRawStatusCode());
580 response.setResponseMessage(exception.getMessage());
583 final String message =
584 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
585 LOGGER.error(message, exception);
586 throw new PolicyException(message, exception);
590 private DecisionResponse getDecisionImpl(final String onapName, final Map<String, String> decisionAttributes,
591 final UUID requestID) throws PolicyDecisionException {
595 final DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters();
596 decisionRequestParameters.setDecisionAttributes(decisionAttributes);
597 decisionRequestParameters.setOnapName(onapName);
598 decisionRequestParameters.setRequestID(requestID);
599 body = PolicyUtils.objectToJsonString(decisionRequestParameters);
600 } catch (final JsonProcessingException e) {
601 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
602 LOGGER.error(message);
603 throw new PolicyDecisionException(message, e);
607 final ResponseEntity<StdDecisionResponse> result =
608 callNewPDP(GET_DECISION_RESOURCE_NAME, HttpMethod.POST, body, StdDecisionResponse.class);
610 return result.getBody();
611 } catch (final Exception exception) {
612 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
613 final String message = getErrorMessage(exception, defaulMessage, GET_DECISION_RESOURCE_NAME);
614 LOGGER.error(message, exception);
615 throw new PolicyDecisionException(message, exception);
619 private Collection<PolicyConfig> getConfigImpl(final ConfigRequestParameters configRequestParameters)
620 throws PolicyConfigException {
624 body = PolicyUtils.objectToJsonString(configRequestParameters);
625 } catch (final JsonProcessingException e) {
626 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
627 LOGGER.error(message);
628 throw new PolicyConfigException(message, e);
632 final ResponseEntity<APIPolicyConfigResponse[]> result =
633 callNewPDP(GET_CONFIG_RESOURCE_NAME, HttpMethod.POST, body, APIPolicyConfigResponse[].class);
635 return configResult(result.getBody());
636 } catch (final Exception exception) {
637 final String defaulMessage = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS + pdps;
638 final String message = getErrorMessage(exception, defaulMessage, GET_CONFIG_RESOURCE_NAME);
639 LOGGER.error(message, exception);
640 throw new PolicyConfigException(message, exception);
644 private ArrayList<PolicyConfig> configResult(final APIPolicyConfigResponse[] response)
645 throws PolicyConfigException {
646 final ArrayList<PolicyConfig> result = new ArrayList<>();
647 if (response == null) {
651 for (final APIPolicyConfigResponse policyConfigResponse : response) {
652 final StdPolicyConfig policyConfig = new StdPolicyConfig();
653 policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage());
654 policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions());
655 policyConfig.setPolicyConfigStatus(policyConfigResponse.getPolicyConfigStatus());
656 policyConfig.setPolicyName(policyConfigResponse.getPolicyName());
657 policyConfig.setPolicyType(policyConfigResponse.getType());
658 policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion());
659 policyConfig.setPolicyType(policyConfigResponse.getPolicyType());
660 policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes());
661 setMatches(policyConfig.getMatchingConditions());
662 if (policyConfigResponse.getType() != null) {
664 switch (policyConfigResponse.getType()) {
666 final StringReader reader = new StringReader(policyConfigResponse.getConfig());
667 try (final JsonReader jsonReader = Json.createReader(reader)) {
668 final JsonObject object = jsonReader.readObject();
669 policyConfig.setJsonObject(object);
673 policyConfig.setOther(policyConfigResponse.getConfig());
676 final Properties props = new Properties();
677 props.putAll(policyConfigResponse.getProperty());
678 policyConfig.setProperties(props);
681 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
682 final DocumentBuilder builder = factory.newDocumentBuilder();
683 final StringReader stringReader = new StringReader(policyConfigResponse.getConfig());
684 policyConfig.setDocument(builder.parse(new InputSource(stringReader)));
687 } catch (final Exception exception) {
688 LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + exception);
689 throw new PolicyConfigException(
690 XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", exception);
693 result.add(policyConfig);
698 private void setMatches(final Map<String, String> matchingConditions) {
699 final Matches match = new Matches();
700 final HashMap<String, String> configAttributes = new HashMap<>();
702 for (final Map.Entry<String, String> entry : matchingConditions.entrySet()) {
703 if (PolicyCommonConfigConstants.ONAP_NAME.equalsIgnoreCase(entry.getKey())) {
704 match.setOnapName(entry.getValue());
705 } else if (PolicyCommonConfigConstants.CONFIG_NAME.equalsIgnoreCase(entry.getKey())) {
706 match.setConfigName(entry.getValue());
708 configAttributes.put(entry.getKey(), entry.getValue());
711 if (!configAttributes.isEmpty()) {
712 match.setConfigAttributes(configAttributes);
714 MatchStore.storeMatch(match);
715 } catch (final Exception e) {
716 LOGGER.error("StoreMatch failed for Onap:" + match.getOnapName() + " Config: " + match.getConfigName(), e);
721 * Generic Rest Client to call PDP services.
723 <T> ResponseEntity<T> callNewPDP(final String resource, final HttpMethod method, final Object body,
724 final Class<T> responseType) throws PolicyException {
725 final RestTemplate restTemplate = new RestTemplate();
726 final HttpEntity<?> requestEntity = new HttpEntity<>(body, getHeaders());
727 ResponseEntity<T> result = null;
728 HttpClientErrorException exception = null;
730 while (pdpsCount < pdps.size()) {
732 result = restTemplate.exchange(pdps.get(0) + "/api/" + resource, method, requestEntity, responseType);
733 } catch (final HttpClientErrorException e) {
734 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
736 } catch (final Exception e) {
737 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
738 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
740 if (result == null) {
741 Collections.rotate(pdps, -1);
742 Collections.rotate(encoding, -1);
748 if (exception == null || exception.getStatusCode() == null) {
752 final String message = getHttpErrorMessage(exception, resource);
753 LOGGER.error(message);
754 throw new PolicyException(message, exception);
757 private String getHttpErrorMessage(final HttpClientErrorException exception, final String resource) {
758 if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
759 return XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + ERROR_AUTH_GET_PERM
762 if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
763 return XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":"
764 + exception.getResponseBodyAsString();
766 if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
767 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps + exception;
769 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":"
770 + exception.getResponseBodyAsString();
773 private HttpHeaders getHeaders() {
774 final HttpHeaders headers = new HttpHeaders();
775 headers.set("ClientAuth", "Basic " + clientEncoding);
776 headers.set("Authorization", "Basic " + encoding.get(0));
777 if (contentType != null) {
778 headers.set("Content-Type", contentType);
780 headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
782 headers.set("Environment", environment);
786 private static void setClientEncoding() {
787 final Base64.Encoder encoder = Base64.getEncoder();
788 clientEncoding = encoder.encodeToString((userName + ":" + pass).getBytes(StandardCharsets.UTF_8));
791 private Collection<String> listConfigImpl(final ConfigRequestParameters listRequestParameters)
792 throws PolicyConfigException {
793 final Collection<String> policyList = new ArrayList<>();
795 policyList.add(TEST_POLICY_NAME);
798 final Collection<PolicyConfig> policyConfig = getConfigImpl(listRequestParameters);
799 for (final PolicyConfig policy : policyConfig) {
800 if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains(PE300)) {
801 policyList.add(policy.getPolicyConfigMessage());
803 policyList.add("Policy Name: " + policy.getPolicyName());
809 public Collection<String> listPolicyImpl(final ConfigNameRequest listPolicyRequestParameters)
810 throws PolicyConfigException {
811 final Collection<String> policyList = new ArrayList<>();
813 policyList.add(TEST_POLICY_NAME);
819 body = PolicyUtils.objectToJsonString(listPolicyRequestParameters);
820 } catch (final JsonProcessingException e) {
821 LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID, e);
822 throw new PolicyConfigException(XACMLErrorConstants.ERROR_SCHEMA_INVALID, e);
826 final ResponseEntity<String[]> result =
827 callNewPDP(LIST_POLICY_RESOURCE_NAME, HttpMethod.POST, body, String[].class);
828 for (final String policy : result.getBody()) {
829 policyList.add(policy);
831 } catch (final Exception exception) {
832 final String defaulMessage = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS + pdps;
833 final String message = getErrorMessage(exception, defaulMessage, LIST_POLICY_RESOURCE_NAME);
834 LOGGER.error(message, exception);
835 throw new PolicyConfigException(message, exception);
841 private Collection<PolicyResponse> sendEventImpl(final Map<String, String> eventAttributes, final UUID requestID)
842 throws PolicyEventException {
846 // Long way here, can be shortened and will be done.
847 final EventRequestParameters eventRequestParameters = new EventRequestParameters();
848 eventRequestParameters.setEventAttributes(eventAttributes);
849 eventRequestParameters.setRequestID(requestID);
850 body = PolicyUtils.objectToJsonString(eventRequestParameters);
851 } catch (final JsonProcessingException e) {
852 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
853 LOGGER.error(message);
854 throw new PolicyEventException(message, e);
858 final ResponseEntity<StdPolicyResponse[]> result =
859 callNewPDP(SEND_EVENT_RESOURCE_NAME, HttpMethod.POST, body, StdPolicyResponse[].class);
861 return eventResult(result.getBody());
862 } catch (final Exception exception) {
863 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
864 final String message = getErrorMessage(exception, defaulMessage, SEND_EVENT_RESOURCE_NAME);
865 LOGGER.error(message, exception);
866 throw new PolicyEventException(message, exception);
870 private String getErrorMessage(final Exception exception, final String defaulMessage, final String resource) {
871 final Throwable cause = exception.getCause();
872 if (cause != null && cause.getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
873 return XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource;
875 if (cause != null && exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
876 return XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
878 return defaulMessage;
881 private ArrayList<PolicyResponse> eventResult(final StdPolicyResponse[] response) {
882 final ArrayList<PolicyResponse> eventResult = new ArrayList<>();
883 if (response != null && response.length > 0) {
884 for (final StdPolicyResponse policyConfigResponse : response) {
885 eventResult.add(policyConfigResponse);
891 private void setProperty(final String propertyFilePath, String clientKey) throws PolicyEngineException {
892 if (propertyFilePath == null) {
893 throw new PolicyEngineException(
894 XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided");
896 final Properties prop = getProperties(propertyFilePath);
897 setProperty(prop, clientKey);
900 private void setProperty(final Properties properties, String clientKey) throws PolicyEngineException {
901 if (properties == null) {
902 throw new PolicyEngineException(
903 XACMLErrorConstants.ERROR_DATA_ISSUE + "NO properties provided, the value is NULL");
906 // UEB and DMAAP Settings
907 final String notificationTypeValue = properties.getProperty(NOTIFICATION_TYPE_PROP_NAME);
908 final String serverList = properties.getProperty(NOTIFICATION_SERVERS_PROP_NAME);
909 topic = properties.getProperty(NOTIFICATION_TOPIC_PROP_NAME);
910 apiKey = properties.getProperty(UEB_API_KEY_PROP_NAME);
911 apiSecret = properties.getProperty(UEB_API_SECRET_PROP_NAME);
913 setNotificationType(notificationTypeValue);
915 if (serverList == null) {
916 notificationType.clear();
917 notificationType.add(DEFAULT_NOTIFICATION);
919 "Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets");
921 notificationURLList = getPropertyValueAsList(serverList.trim());
925 topic = topic.trim();
927 LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter.");
930 // Client ID Authorization Settings.
931 final String clientID = properties.getProperty(CLIENT_ID_PROP_NAME);
932 if (clientKey == null) {
933 clientKey = getClientKeyFromProperties(properties);
935 if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) {
936 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
937 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
938 throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS
939 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
941 setClientId(clientID.trim());
942 setClientKey(clientKey.trim());
944 setEnvironment(properties);
945 // Initializing the values.
947 readPdpProperites(properties);
948 // Get JUNIT property from properties file when running tests
949 checkJunit(properties);
952 private void readPdpProperites(final Properties prop) throws PolicyEngineException {
953 // Check the Keys for PDP_URLs
954 for (final String propertyKey : prop.stringPropertyNames()) {
955 if (propertyKey.startsWith(PDP_URL_PROP_NAME)) {
956 readPDPPropertyURL(prop, propertyKey);
959 if (pdps == null || pdps.isEmpty()) {
960 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
961 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
965 private void readPDPPropertyURL(Properties prop, String propertyKey) throws PolicyEngineException {
966 final String propertyValue = prop.getProperty(propertyKey);
967 if (propertyValue == null) {
968 throw new PolicyEngineException(
969 XACMLErrorConstants.ERROR_DATA_ISSUE + "Properties file doesn't have the PDP_URL parameter");
971 if (propertyValue.contains(SEMICOLLON)) {
972 final List<String> pdpDefault = Arrays.asList(propertyValue.split(REGEX));
973 for (final String pdpVal : pdpDefault) {
974 readPDPParam(pdpVal);
977 readPDPParam(propertyValue);
981 private void setNotificationType(final String propertyValue) {
982 if (propertyValue == null) {
983 notificationType.add(DEFAULT_NOTIFICATION);
985 "Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets");
987 notificationType = getPropertyValueAsList(propertyValue.trim());
991 private String getClientKeyFromProperties(final Properties prop) {
992 final String clientKeyValue = prop.getProperty(CLIENT_KEY_PROP_NAME);
994 return PolicyUtils.decode(clientKeyValue);
995 } catch (UnsupportedEncodingException | IllegalArgumentException e) {
996 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
997 + " Cannot Decode the given Password Proceeding with given Password!!", e);
999 return clientKeyValue;
1002 private Properties getProperties(final String propertyFilePath) throws PolicyEngineException {
1003 // Adding logic for remote Properties file.
1004 if (propertyFilePath.startsWith(HTTP)) {
1005 return getRemoteProperties(propertyFilePath);
1007 return getFileProperties(propertyFilePath);
1010 private Properties getFileProperties(final String propertyFilePath) throws PolicyEngineException {
1011 final Path file = Paths.get(propertyFilePath);
1012 if (!file.toFile().exists()) {
1013 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
1014 + "File doesn't exist in the specified Path " + file.toString());
1016 if (file.toString().endsWith(".properties")) {
1017 try (BufferedReader bufferedReader = Files.newBufferedReader(file);) {
1018 final Properties prop = new Properties();
1019 prop.load(bufferedReader);
1021 } catch (final IOException exception) {
1022 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + exception);
1023 throw new PolicyEngineException(
1024 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", exception);
1027 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath);
1028 throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file");
1031 private Properties getRemoteProperties(final String propertyFilePath) throws PolicyEngineException {
1033 final URL configURL = new URL(propertyFilePath);
1034 final URLConnection connection = configURL.openConnection();
1035 final Properties prop = new Properties();
1036 prop.load(connection.getInputStream());
1038 } catch (final IOException e) {
1039 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1040 throw new PolicyEngineException(
1041 XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage());
1045 private List<String> getPropertyValueAsList(final String propertyValue) {
1046 if (propertyValue.contains(COMMA)) {
1047 return Arrays.asList(propertyValue.split(COMMA));
1049 final List<String> valuesList = new ArrayList<>();
1050 valuesList.add(propertyValue);
1054 private static void checkJunit(final Properties prop) {
1055 final String junitFlag = prop.getProperty(JUNIT_PROP_NAME);
1056 if (junitFlag == null || junitFlag.isEmpty()) {
1057 LOGGER.info("No JUNIT property provided, this will not be executed as a test.");
1059 if ("test".equalsIgnoreCase(junitFlag)) {
1060 StdPolicyEngine.junit = true;
1062 StdPolicyEngine.junit = false;
1067 private static void init() {
1068 pdps = new ArrayList<>();
1069 encoding = new ArrayList<>();
1072 private static void setEnvironment(final Properties prop) {
1073 environment = prop.getProperty(ENVIRONMENT_PROP_NAME, AAFEnvironment.DEVL.toString());
1074 if (environment.equalsIgnoreCase(AAFEnvironment.TEST.toString())) {
1075 environment = AAFEnvironment.TEST.toString();
1076 } else if (environment.equalsIgnoreCase(AAFEnvironment.PROD.toString())) {
1077 environment = AAFEnvironment.PROD.toString();
1079 environment = AAFEnvironment.DEVL.toString();
1083 private static void setClientId(final String clientID) {
1084 userName = clientID;
1088 * Read the PDP_URL parameter
1090 private void readPDPParam(final String pdpVal) throws PolicyEngineException {
1091 if (pdpVal.contains(COMMA)) {
1092 final List<String> pdpValues = Arrays.asList(pdpVal.split(PDP_VALUE_REGEX));
1093 if (pdpValues.size() == 3) {
1095 pdps.add(pdpValues.get(0));
1096 // 1:2 will be UserID:Password
1097 final String userID = pdpValues.get(1);
1098 final String userPas = pdpValues.get(2);
1099 final Base64.Encoder encoder = Base64.getEncoder();
1100 encoding.add(encoder.encodeToString((userID + ":" + userPas).getBytes(StandardCharsets.UTF_8)));
1102 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues);
1103 throw new PolicyEngineException(
1104 XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues);
1108 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal);
1109 throw new PolicyEngineException(
1110 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values.");
1115 * Allowing changes to the scheme and Handler.
1117 public void notification(final NotificationScheme scheme, final NotificationHandler handler) {
1118 this.scheme = scheme;
1119 this.handler = handler;
1120 LOGGER.debug("Scheme is : " + scheme.toString());
1121 LOGGER.debug("Handler is : " + handler.getClass().getName());
1123 if (UEB.equals(notificationType.get(0))) {
1124 if (this.uebThread) {
1125 AutoClientUEB.setAuto(scheme, handler);
1126 this.uebThread = registerUEBThread.isAlive();
1128 } else if (notificationType.get(0).equals(DMAAP)) {
1129 if (this.dmaapThread) {
1130 AutoClientDMAAP.setAuto(scheme, handler);
1131 this.dmaapThread = registerDMAAPThread.isAlive();
1134 AutoClientEnd.setAuto(scheme, handler);
1144 if (UEB.equals(notificationType.get(0)) && !this.uebThread) {
1145 this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret);
1146 AutoClientUEB.setAuto(scheme, handler);
1147 this.registerUEBThread = new Thread(this.uebClientThread);
1148 this.registerUEBThread.start();
1149 this.uebThread = true;
1150 } else if (notificationType.get(0).equals(DMAAP) && !this.dmaapThread) {
1151 this.dmaapClientThread = new AutoClientDMAAP(notificationURLList, topic, userName, pass);
1152 AutoClientDMAAP.setAuto(scheme, handler);
1153 this.registerDMAAPThread = new Thread(this.dmaapClientThread);
1154 this.registerDMAAPThread.start();
1155 this.dmaapThread = true;
1157 if (pdps.get(0) != null) {
1158 if (AutoClientEnd.getUrl() == null) {
1159 AutoClientEnd.start(pdps.get(0));
1161 AutoClientEnd.stop();
1162 AutoClientEnd.start(pdps.get(0));
1169 * Gets the Notification if one exists. Used only for Manual Polling purposes.
1171 public PDPNotification getNotification() {
1172 // Check if there is proper scheme..
1173 PDPNotification notification;
1174 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)
1175 || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
1176 if (UEB.equals(notificationType.get(0))) {
1177 ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID);
1178 notification = ManualClientEndUEB.result(scheme);
1179 } else if (notificationType.get(0).equals(DMAAP)) {
1180 ManualClientEndDMAAP.start(notificationURLList, topic, UNIQUEID, userName, pass);
1181 notification = ManualClientEndDMAAP.result(scheme);
1183 ManualClientEnd.start(pdps.get(0));
1184 LOGGER.debug("manual notification requested.. : " + scheme.toString());
1185 notification = ManualClientEnd.result(scheme);
1187 if (notification == null) {
1188 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet..");
1191 return notification;
1197 * Setting the Scheme.
1199 public void setScheme(final NotificationScheme scheme) {
1200 this.scheme = scheme;
1201 if (UEB.equals(notificationType.get(0))) {
1202 AutoClientUEB.setScheme(this.scheme);
1203 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1204 ManualClientEndUEB.createTopic(pdps.get(0), UNIQUEID, notificationURLList);
1206 } else if (notificationType.get(0).equals(DMAAP)) {
1207 AutoClientDMAAP.setScheme(this.scheme);
1208 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1209 ManualClientEndDMAAP.createTopic(topic, UNIQUEID, notificationURLList, userName, pass);
1212 AutoClientEnd.setScheme(this.scheme);
1217 * Returns the Scheme
1219 public NotificationScheme getScheme() {
1224 * Returns the NotificationHandler
1226 public NotificationHandler getNotificationHandler() {
1227 return this.handler;
1231 * Stop the Notification Service if its running.
1233 public void stopNotification() {
1234 if (this.scheme != null && this.handler != null
1235 && (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)
1236 || this.scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS))) {
1237 LOGGER.info("Clear Notification called.. ");
1238 if (UEB.equals(notificationType.get(0))) {
1239 this.uebClientThread.terminate();
1240 this.uebThread = false;
1241 } else if (notificationType.get(0).equals(DMAAP)) {
1242 this.dmaapClientThread.terminate();
1243 this.dmaapThread = false;
1245 AutoClientEnd.stop();
1251 * Push a policy to the PDP API implementation
1253 public String pushPolicy(final String policyScope, final String policyName, final String policyType,
1254 final String pdpGroup, final UUID requestID) throws PolicyException {
1255 validateParameters(policyName, policyScope);
1257 final PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
1258 pushPolicyParameters.setPolicyName(policyScope + "." + policyName);
1259 pushPolicyParameters.setPolicyType(policyType);
1260 pushPolicyParameters.setPdpGroup(pdpGroup);
1261 pushPolicyParameters.setRequestID(requestID);
1262 return pushPolicyImpl(pushPolicyParameters).getResponseMessage();
1265 private boolean isNotValid(final String value) {
1266 return value == null || value.trim().isEmpty();
1269 public String createUpdateConfigPolicy(final String policyName, final String policyDescription,
1270 final String onapName, final String configName, final Map<String, String> configAttributes,
1271 final String configType, final String body, final String policyScope, final UUID requestID,
1272 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1273 final boolean updateFlag) throws PolicyException {
1274 return createUpdateConfigPolicyImpl(policyName, policyDescription, onapName, configName, configAttributes,
1275 configType, body, policyScope, requestID, riskLevel, riskType, guard, ttlDate, updateFlag);
1279 * Create Config Policy API Implementation
1281 private String createUpdateConfigPolicyImpl(final String policyName, final String policyDescription,
1282 final String onapName, final String configName, final Map<String, String> configAttributes,
1283 final String configType, final String body, final String policyScope, final UUID requestID,
1284 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1285 final boolean updateFlag) throws PolicyException {
1287 validateParameters(policyName, policyScope);
1289 final PolicyParameters policyParameters = new PolicyParameters();
1290 policyParameters.setPolicyClass(PolicyClass.Config);
1291 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
1292 policyParameters.setPolicyName(policyScope + "." + policyName);
1293 policyParameters.setPolicyDescription(policyDescription);
1294 policyParameters.setOnapName(onapName);
1295 policyParameters.setConfigName(configName);
1297 final Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
1298 attributes.put(AttributeType.MATCHING, configAttributes);
1300 policyParameters.setAttributes(attributes);
1301 policyParameters.setConfigBodyType(PolicyType.valueOf(configType));
1302 policyParameters.setConfigBody(body);
1303 policyParameters.setRequestID(requestID);
1304 policyParameters.setRiskLevel(riskLevel);
1305 policyParameters.setRiskType(riskType);
1306 policyParameters.setGuard(Boolean.parseBoolean(guard));
1307 policyParameters.setTtlDate(toDate(ttlDate));
1308 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1311 private Date toDate(final String dateString) {
1313 return new SimpleDateFormat(DATE_FORMAT).parse(dateString);
1314 } catch (final ParseException e) {
1315 LOGGER.warn("Error Parsing date given " + dateString);
1320 public String createUpdateConfigFirewallPolicy(final String policyName, final JsonObject firewallJson,
1321 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1322 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1323 return createUpdateConfigFirewallPolicyImpl(policyName, firewallJson, policyScope, requestID, riskLevel,
1324 riskType, guard, ttlDate, updateFlag);
1328 * Create Update Config Firewall Policy API implementation
1330 private String createUpdateConfigFirewallPolicyImpl(final String policyName, final JsonObject firewallJson,
1331 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1332 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1333 validateParameters(policyName, policyScope);
1335 final PolicyParameters policyParameters = new PolicyParameters();
1336 policyParameters.setPolicyClass(PolicyClass.Config);
1337 policyParameters.setPolicyConfigType(PolicyConfigType.Firewall);
1338 policyParameters.setPolicyName(policyScope + "." + policyName);
1339 policyParameters.setConfigBody(firewallJson.toString());
1340 policyParameters.setRequestID(requestID);
1341 policyParameters.setRiskLevel(riskLevel);
1342 policyParameters.setRiskType(riskType);
1343 policyParameters.setGuard(Boolean.parseBoolean(guard));
1344 policyParameters.setTtlDate(toDate(ttlDate));
1345 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1348 private void validateParameters(final String policyName, final String policyScope) throws PolicyException {
1349 if (isNotValid(policyScope)) {
1350 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
1351 LOGGER.error(message);
1352 throw new PolicyException(message);
1354 if (isNotValid(policyName)) {
1355 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
1356 LOGGER.error(message);
1357 throw new PolicyException(message);
1361 public static void setClientKey(final String clientKey) {
1362 if (clientKey != null && !clientKey.isEmpty()) {
1363 StdPolicyEngine.pass = clientKey;
1364 setClientEncoding();
1369 * Get the Environment.
1371 public static String getEnvironment() {
1376 * Rotate the PDP list upon WEBsocket Failures
1378 public static void rotatePDPList() {
1379 Collections.rotate(pdps, -1);
1380 Collections.rotate(encoding, -1);
1384 * Get the latest PDP
1386 public static String getPDPURL() {
1396 List<String> getNotificationType() {
1397 return notificationType;
1401 List<String> getNotificationURLList() {
1402 return notificationURLList;