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.PeCryptoUtils;
129 import org.onap.policy.utils.PolicyUtils;
130 import org.onap.policy.xacml.api.XACMLErrorConstants;
131 import org.springframework.core.io.FileSystemResource;
132 import org.springframework.http.HttpEntity;
133 import org.springframework.http.HttpHeaders;
134 import org.springframework.http.HttpMethod;
135 import org.springframework.http.HttpStatus;
136 import org.springframework.http.MediaType;
137 import org.springframework.http.ResponseEntity;
138 import org.springframework.util.LinkedMultiValueMap;
139 import org.springframework.web.client.HttpClientErrorException;
140 import org.springframework.web.client.RestTemplate;
141 import org.xml.sax.InputSource;
144 * PolicyEngine Implementation class
148 public class StdPolicyEngine {
150 private static String clientEncoding = null;
151 private String contentType = null;
152 private static List<String> pdps = null;
153 private static String environment = null;
154 private static String userName = null;
155 private static String pass = null;
156 private static List<String> encoding = null;
157 private static boolean junit = false;
158 private List<String> notificationType = new ArrayList<>();
159 private List<String> notificationURLList = new ArrayList<>();
160 private NotificationScheme scheme = null;
161 private NotificationHandler handler = null;
162 private AutoClientUEB uebClientThread = null;
163 private Thread registerUEBThread = null;
164 private boolean uebThread = false;
165 private AutoClientDMAAP dmaapClientThread = null;
166 private Thread registerDMAAPThread = null;
167 private boolean dmaapThread = false;
168 private String topic = null;
169 private String apiKey = null;
170 private String apiSecret = null;
172 private static final String UNIQUEID = UUID.randomUUID().toString();
173 private static final Logger LOGGER = FlexLogger.getLogger(StdPolicyConfig.class.getName());
174 private static final String LIST_POLICY_RESOURCE_NAME = "listPolicy";
177 * Taking the Property file even if it null.
179 public StdPolicyEngine(final String propertyFilePath, final String clientKey) throws PolicyEngineException {
180 setProperty(propertyFilePath, clientKey);
184 * Taking the Property structure even if it null.
186 public StdPolicyEngine(final Properties properties, final String clientKey) throws PolicyEngineException {
187 setProperty(properties, clientKey);
191 * Taking the Notification Constructor.
193 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme,
194 final NotificationHandler handler) throws PolicyEngineException {
195 setProperty(propertyFilePath, null);
196 this.scheme = scheme;
197 this.handler = handler;
198 if ((!UEB.equals(notificationType.get(0))) || (!DMAAP.equals(notificationType.get(0)))) {
199 AutoClientEnd.setAuto(scheme, handler);
201 notification(scheme, handler);
205 * Taking the Notification Constructor.
207 public StdPolicyEngine(final String propertyFilePath, final NotificationScheme scheme)
208 throws PolicyEngineException {
209 setProperty(propertyFilePath, null);
210 this.scheme = scheme;
215 * sendEvent API Implementation
217 public Collection<PolicyResponse> sendEvent(final Map<String, String> eventAttributes, final UUID requestID)
218 throws PolicyEventException {
219 return sendEventImpl(eventAttributes, requestID);
223 * sendEvent API Implementation for eventRequestParameters
225 public Collection<PolicyResponse> sendEvent(final EventRequestParameters eventRequestParameters)
226 throws PolicyEventException {
227 if (eventRequestParameters == null) {
228 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Request Parameters Given. ";
229 LOGGER.error(message);
230 throw new PolicyEventException(message);
232 return sendEventImpl(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID());
236 * getConfig using configRequestParameters Implementation
238 public Collection<PolicyConfig> getConfig(final ConfigRequestParameters configRequestParameters)
239 throws PolicyConfigException {
240 return getConfigImpl(configRequestParameters);
244 * listPolicies using configRequestParameters Implementation
246 public Collection<String> listConfig(final ConfigRequestParameters listPolicyRequestParameters)
247 throws PolicyConfigException {
248 return listConfigImpl(listPolicyRequestParameters);
252 * listPolicies from PDP using ConfigNameRequest Implementation
254 public Collection<String> listPolicy(final ConfigNameRequest listPolicyRequestParameters)
255 throws PolicyConfigException {
256 return listPolicyImpl(listPolicyRequestParameters);
260 * getDecision using the decision Attributes.
262 public DecisionResponse getDecision(final String onapName, final Map<String, String> decisionAttributes,
263 final UUID requestID) throws PolicyDecisionException {
264 return getDecisionImpl(onapName, decisionAttributes, requestID);
268 * getDecision Using decisionRequestParameters.
270 public DecisionResponse getDecision(final DecisionRequestParameters decisionRequestParameters)
271 throws PolicyDecisionException {
272 if (decisionRequestParameters == null) {
273 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Request Parameters Given. ";
274 LOGGER.error(message);
275 throw new PolicyDecisionException(message);
277 return getDecisionImpl(decisionRequestParameters.getOnapName(),
278 decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID());
282 * getMetrics using metricsRequestParameters
284 public MetricsResponse getMetrics(final MetricsRequestParameters parameters) throws PolicyException {
285 return getMetricsImpl(parameters);
288 public MetricsResponse getMetricsImpl(final MetricsRequestParameters parameters) throws PolicyException {
290 // Create the Request
292 if (parameters != null) {
293 body = PolicyUtils.objectToJsonString(parameters);
295 } catch (final JsonProcessingException jsonProcessingException) {
296 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
297 LOGGER.error(message);
298 throw new PolicyException(message, jsonProcessingException);
301 final StdMetricsResponse response = new StdMetricsResponse();
304 final ResponseEntity<String> result =
305 callNewPDP(GET_METRICS_RESOURCE_NAME, HttpMethod.GET, body, String.class);
307 response.setResponseMessage(result.getBody());
308 response.setResponseCode(result.getStatusCode().value());
310 } catch (final PolicyException exception) {
311 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
312 LOGGER.error(exception);
313 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
314 response.setResponseCode(ex.getRawStatusCode());
315 response.setResponseMessage(exception.getMessage());
318 final String message =
319 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
320 LOGGER.error(message, exception);
321 throw new PolicyException(message, exception);
326 * PushPolicy using pushPolicyParameters.
328 public PolicyChangeResponse pushPolicy(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
329 return pushPolicyImpl(pushPolicyParameters);
332 public PolicyChangeResponse pushPolicyImpl(final PushPolicyParameters pushPolicyParameters) throws PolicyException {
333 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
337 body = PolicyUtils.objectToJsonString(pushPolicyParameters);
338 } catch (final JsonProcessingException e) {
339 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
340 LOGGER.error(message);
341 throw new PolicyException(message, e);
345 final ResponseEntity<String> result =
346 callNewPDP(PUSH_POLICY_RESOURCE_NAME, HttpMethod.PUT, body, String.class);
348 response.setResponseMessage(result.getBody());
349 response.setResponseCode(result.getStatusCode().value());
351 } catch (final PolicyException exception) {
352 return processException(exception);
357 * Delete a Policy using deletePolicyParameters
359 public PolicyChangeResponse deletePolicy(final DeletePolicyParameters parameters) throws PolicyException {
360 return deletePolicyImpl(parameters);
363 private PolicyChangeResponse deletePolicyImpl(final DeletePolicyParameters parameters) throws PolicyException {
364 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
368 body = PolicyUtils.objectToJsonString(parameters);
369 } catch (final JsonProcessingException e) {
370 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
371 LOGGER.error(message);
372 throw new PolicyException(message, e);
376 final ResponseEntity<String> result =
377 callNewPDP(DELETE_POLICY_RESOURCE_NAME, HttpMethod.DELETE, body, String.class);
379 response.setResponseMessage(result.getBody());
380 response.setResponseCode(result.getStatusCode().value());
381 } catch (final PolicyException exception) {
382 return processException(exception);
388 * getDictionaryItem Using dictionaryParameters
390 public DictionaryResponse getDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
391 return getDictionaryItemImpl(parameters);
394 private DictionaryResponse getDictionaryItemImpl(final DictionaryParameters parameters) throws PolicyException {
395 final StdDictionaryResponse response = new StdDictionaryResponse();
399 body = PolicyUtils.objectToJsonString(parameters);
400 } catch (final JsonProcessingException e) {
401 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
402 LOGGER.error(message);
403 throw new PolicyException(message, e);
407 final ResponseEntity<APIDictionaryResponse> result =
408 callNewPDP(GET_DICTIONARY_ITEMS_RESOURCE_NAME, HttpMethod.POST, body, APIDictionaryResponse.class);
410 return dictionaryResult(result.getBody());
411 } catch (final Exception exception) {
412 if (exception.getCause().getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
413 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM
414 + GET_DICTIONARY_ITEMS_RESOURCE_NAME;
415 LOGGER.error(message);
416 response.setResponseMessage(message);
417 response.setResponseCode(HttpStatus.UNAUTHORIZED.value());
420 if (exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
421 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
422 response.setResponseMessage(message);
423 response.setResponseCode(HttpStatus.BAD_REQUEST.value());
426 final String message = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
427 LOGGER.error(message, exception);
428 response.setResponseMessage(message);
429 response.setResponseCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
434 @SuppressWarnings("unchecked")
435 private StdDictionaryResponse dictionaryResult(final APIDictionaryResponse body) {
436 final StdDictionaryResponse response = new StdDictionaryResponse();
437 response.setResponseCode(body.getResponseCode());
438 response.setResponseMessage(body.getResponseMessage());
439 response.setDictionaryData((Map<String, String>) body.getDictionaryData());
440 if (body.getDictionaryJson() != null) {
441 final Gson objGson = new GsonBuilder().create();
442 final String mapToJson = objGson.toJson(body.getDictionaryJson());
443 try (final JsonReader jsonReader = Json.createReader(new StringReader(mapToJson));) {
444 final JsonObject object = jsonReader.readObject();
445 response.setDictionaryJson(object);
452 * createDictinaryItem Using dictionaryParameters.
454 public PolicyChangeResponse createDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
455 return createUpdateDictionaryItemImpl(parameters, false);
459 * updateDictinaryItem Using dictionaryParameters.
461 public PolicyChangeResponse updateDictionaryItem(final DictionaryParameters parameters) throws PolicyException {
462 return createUpdateDictionaryItemImpl(parameters, true);
465 private PolicyChangeResponse createUpdateDictionaryItemImpl(final DictionaryParameters parameters,
466 final boolean updateFlag) throws PolicyException {
468 final String resource = getDictionaryResouceName(updateFlag);
472 body = PolicyUtils.objectToJsonString(parameters);
473 } catch (final JsonProcessingException jsonProcessingException) {
474 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + jsonProcessingException;
475 LOGGER.error(message);
476 throw new PolicyException(message, jsonProcessingException);
480 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
481 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
483 response.setResponseMessage(result.getBody());
484 response.setResponseCode(result.getStatusCode().value());
486 } catch (final PolicyException exception) {
487 return processException(exception);
491 private String getDictionaryResouceName(final boolean updateFlag) {
492 return updateFlag ? UPDATE_DICTIONARY_ITEM_RESOURCE_NAME : CREATE_DICTIONARY_ITEM_RESOURCE_NAME;
496 * PolicyEngine Import
498 public PolicyChangeResponse policyEngineImport(final ImportParameters importParameters) throws PolicyException {
499 return policyEngineImportImpl(importParameters);
502 private PolicyChangeResponse policyEngineImportImpl(final ImportParameters importParameters)
503 throws PolicyException {
504 final LinkedMultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
507 final String body = PolicyUtils.objectToJsonString(importParameters);
508 parameters.set("importParametersJson", body);
509 parameters.set("file", new FileSystemResource(importParameters.getFilePath()));
510 } catch (final Exception e) {
511 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
512 LOGGER.error(message);
513 throw new PolicyException(message, e);
515 contentType = MediaType.MULTIPART_FORM_DATA_VALUE;
518 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
519 final ResponseEntity<String> result =
520 callNewPDP(POLICY_ENGINE_IMPORT_RESOURCE_NAME, HttpMethod.POST, parameters, String.class);
522 response.setResponseMessage(result.getBody());
523 response.setResponseCode(result.getStatusCode().value());
525 } catch (final PolicyException exception) {
526 return processException(exception);
533 * createPolicy Using policyParameters.
535 public PolicyChangeResponse createPolicy(final PolicyParameters policyParameters) throws PolicyException {
536 return createUpdatePolicyImpl(policyParameters, false);
540 * updatePolicy using policyParameters.
542 public PolicyChangeResponse updatePolicy(final PolicyParameters policyParameters) throws PolicyException {
543 return createUpdatePolicyImpl(policyParameters, true);
546 private PolicyChangeResponse createUpdatePolicyImpl(final PolicyParameters policyParameters,
547 final boolean updateFlag) throws PolicyException {
548 final String resource = getPolicyResourceName(updateFlag);
552 body = PolicyUtils.objectToJsonString(policyParameters);
553 } catch (final JsonProcessingException e) {
554 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
555 LOGGER.error(message);
556 throw new PolicyException(message, e);
560 final ResponseEntity<String> result = callNewPDP(resource, HttpMethod.PUT, body, String.class);
561 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
563 response.setResponseMessage(result.getBody());
564 response.setResponseCode(result.getStatusCode().value());
566 } catch (final PolicyException exception) {
567 return processException(exception);
571 private String getPolicyResourceName(final boolean updateFlag) {
572 return updateFlag ? UPDATE_POLICY_RESOURCE_NAME : CREATE_POLICY_RESOURCE_NAME;
575 private PolicyChangeResponse processException(final PolicyException exception) throws PolicyException {
576 final StdPolicyChangeResponse response = new StdPolicyChangeResponse();
577 if (exception.getCause() != null && exception.getCause() instanceof HttpClientErrorException) {
578 LOGGER.error(exception);
579 final HttpClientErrorException ex = (HttpClientErrorException) exception.getCause();
580 response.setResponseCode(ex.getRawStatusCode());
581 response.setResponseMessage(exception.getMessage());
584 final String message =
585 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error while processing results. please check logs.";
586 LOGGER.error(message, exception);
587 throw new PolicyException(message, exception);
591 private DecisionResponse getDecisionImpl(final String onapName, final Map<String, String> decisionAttributes,
592 final UUID requestID) throws PolicyDecisionException {
596 final DecisionRequestParameters decisionRequestParameters = new DecisionRequestParameters();
597 decisionRequestParameters.setDecisionAttributes(decisionAttributes);
598 decisionRequestParameters.setOnapName(onapName);
599 decisionRequestParameters.setRequestID(requestID);
600 body = PolicyUtils.objectToJsonString(decisionRequestParameters);
601 } catch (final JsonProcessingException e) {
602 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
603 LOGGER.error(message);
604 throw new PolicyDecisionException(message, e);
608 final ResponseEntity<StdDecisionResponse> result =
609 callNewPDP(GET_DECISION_RESOURCE_NAME, HttpMethod.POST, body, StdDecisionResponse.class);
611 return result.getBody();
612 } catch (final Exception exception) {
613 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
614 final String message = getErrorMessage(exception, defaulMessage, GET_DECISION_RESOURCE_NAME);
615 LOGGER.error(message, exception);
616 throw new PolicyDecisionException(message, exception);
620 private Collection<PolicyConfig> getConfigImpl(final ConfigRequestParameters configRequestParameters)
621 throws PolicyConfigException {
625 body = PolicyUtils.objectToJsonString(configRequestParameters);
626 } catch (final JsonProcessingException e) {
627 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
628 LOGGER.error(message);
629 throw new PolicyConfigException(message, e);
633 final ResponseEntity<APIPolicyConfigResponse[]> result =
634 callNewPDP(GET_CONFIG_RESOURCE_NAME, HttpMethod.POST, body, APIPolicyConfigResponse[].class);
636 return configResult(result.getBody());
637 } catch (final Exception exception) {
638 final String defaulMessage = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS + pdps;
639 final String message = getErrorMessage(exception, defaulMessage, GET_CONFIG_RESOURCE_NAME);
640 LOGGER.error(message, exception);
641 throw new PolicyConfigException(message, exception);
645 private ArrayList<PolicyConfig> configResult(final APIPolicyConfigResponse[] response)
646 throws PolicyConfigException {
647 final ArrayList<PolicyConfig> result = new ArrayList<>();
648 if (response == null) {
652 for (final APIPolicyConfigResponse policyConfigResponse : response) {
653 final StdPolicyConfig policyConfig = new StdPolicyConfig();
654 policyConfig.setConfigStatus(policyConfigResponse.getPolicyConfigMessage());
655 policyConfig.setMatchingConditions(policyConfigResponse.getMatchingConditions());
656 policyConfig.setPolicyConfigStatus(policyConfigResponse.getPolicyConfigStatus());
657 policyConfig.setPolicyName(policyConfigResponse.getPolicyName());
658 policyConfig.setPolicyType(policyConfigResponse.getType());
659 policyConfig.setPolicyVersion(policyConfigResponse.getPolicyVersion());
660 policyConfig.setPolicyType(policyConfigResponse.getPolicyType());
661 policyConfig.setResponseAttributes(policyConfigResponse.getResponseAttributes());
662 setMatches(policyConfig.getMatchingConditions());
663 if (policyConfigResponse.getType() != null) {
665 switch (policyConfigResponse.getType()) {
667 final StringReader reader = new StringReader(policyConfigResponse.getConfig());
668 try (final JsonReader jsonReader = Json.createReader(reader)) {
669 final JsonObject object = jsonReader.readObject();
670 policyConfig.setJsonObject(object);
674 policyConfig.setOther(policyConfigResponse.getConfig());
677 final Properties props = new Properties();
678 props.putAll(policyConfigResponse.getProperty());
679 policyConfig.setProperties(props);
682 final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
683 final DocumentBuilder builder = factory.newDocumentBuilder();
684 final StringReader stringReader = new StringReader(policyConfigResponse.getConfig());
685 policyConfig.setDocument(builder.parse(new InputSource(stringReader)));
688 } catch (final Exception exception) {
689 LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + exception);
690 throw new PolicyConfigException(
691 XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to parse the config", exception);
694 result.add(policyConfig);
699 private void setMatches(final Map<String, String> matchingConditions) {
700 final Matches match = new Matches();
701 final HashMap<String, String> configAttributes = new HashMap<>();
703 for (final Map.Entry<String, String> entry : matchingConditions.entrySet()) {
704 if (PolicyCommonConfigConstants.ONAP_NAME.equalsIgnoreCase(entry.getKey())) {
705 match.setOnapName(entry.getValue());
706 } else if (PolicyCommonConfigConstants.CONFIG_NAME.equalsIgnoreCase(entry.getKey())) {
707 match.setConfigName(entry.getValue());
709 configAttributes.put(entry.getKey(), entry.getValue());
712 if (!configAttributes.isEmpty()) {
713 match.setConfigAttributes(configAttributes);
715 MatchStore.storeMatch(match);
716 } catch (final Exception e) {
717 LOGGER.error("StoreMatch failed for Onap:" + match.getOnapName() + " Config: " + match.getConfigName(), e);
722 * Generic Rest Client to call PDP services.
724 <T> ResponseEntity<T> callNewPDP(final String resource, final HttpMethod method, final Object body,
725 final Class<T> responseType) throws PolicyException {
726 final RestTemplate restTemplate = new RestTemplate();
727 final HttpEntity<?> requestEntity = new HttpEntity<>(body, getHeaders());
728 ResponseEntity<T> result = null;
729 HttpClientErrorException exception = null;
731 while (pdpsCount < pdps.size()) {
733 result = restTemplate.exchange(pdps.get(0) + "/api/" + resource, method, requestEntity, responseType);
734 } catch (final HttpClientErrorException e) {
735 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
737 } catch (final Exception e) {
738 LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps.get(0), e);
739 exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage());
741 if (result == null) {
742 Collections.rotate(pdps, -1);
743 Collections.rotate(encoding, -1);
749 if (exception == null || exception.getStatusCode() == null) {
753 final String message = getHttpErrorMessage(exception, resource);
754 LOGGER.error(message);
755 throw new PolicyException(message, exception);
758 private String getHttpErrorMessage(final HttpClientErrorException exception, final String resource) {
759 if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) {
760 return XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + ERROR_AUTH_GET_PERM
763 if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) {
764 return XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":"
765 + exception.getResponseBodyAsString();
767 if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) {
768 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_WHILE_CONNECTING + pdps + exception;
770 return XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":"
771 + exception.getResponseBodyAsString();
774 private HttpHeaders getHeaders() {
775 final HttpHeaders headers = new HttpHeaders();
776 headers.set("ClientAuth", "Basic " + clientEncoding);
777 headers.set("Authorization", "Basic " + encoding.get(0));
778 if (contentType != null) {
779 headers.set("Content-Type", contentType);
781 headers.set("Content-Type", MediaType.APPLICATION_JSON_VALUE);
783 headers.set("Environment", environment);
787 private static void setClientEncoding() {
788 final Base64.Encoder encoder = Base64.getEncoder();
789 clientEncoding = encoder.encodeToString((userName + ":" + pass).getBytes(StandardCharsets.UTF_8));
792 private Collection<String> listConfigImpl(final ConfigRequestParameters listRequestParameters)
793 throws PolicyConfigException {
794 final Collection<String> policyList = new ArrayList<>();
796 policyList.add(TEST_POLICY_NAME);
799 final Collection<PolicyConfig> policyConfig = getConfigImpl(listRequestParameters);
800 for (final PolicyConfig policy : policyConfig) {
801 if (policy.getPolicyConfigMessage() != null && policy.getPolicyConfigMessage().contains(PE300)) {
802 policyList.add(policy.getPolicyConfigMessage());
804 policyList.add("Policy Name: " + policy.getPolicyName());
810 public Collection<String> listPolicyImpl(final ConfigNameRequest listPolicyRequestParameters)
811 throws PolicyConfigException {
812 final Collection<String> policyList = new ArrayList<>();
814 policyList.add(TEST_POLICY_NAME);
820 body = PolicyUtils.objectToJsonString(listPolicyRequestParameters);
821 } catch (final JsonProcessingException e) {
822 LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID, e);
823 throw new PolicyConfigException(XACMLErrorConstants.ERROR_SCHEMA_INVALID, e);
827 final ResponseEntity<String[]> result =
828 callNewPDP(LIST_POLICY_RESOURCE_NAME, HttpMethod.POST, body, String[].class);
829 for (final String policy : result.getBody()) {
830 policyList.add(policy);
832 } catch (final Exception exception) {
833 final String defaulMessage = XACMLErrorConstants.ERROR_PROCESS_FLOW + ERROR_INVALID_PDPS + pdps;
834 final String message = getErrorMessage(exception, defaulMessage, LIST_POLICY_RESOURCE_NAME);
835 LOGGER.error(message, exception);
836 throw new PolicyConfigException(message, exception);
842 private Collection<PolicyResponse> sendEventImpl(final Map<String, String> eventAttributes, final UUID requestID)
843 throws PolicyEventException {
847 // Long way here, can be shortened and will be done.
848 final EventRequestParameters eventRequestParameters = new EventRequestParameters();
849 eventRequestParameters.setEventAttributes(eventAttributes);
850 eventRequestParameters.setRequestID(requestID);
851 body = PolicyUtils.objectToJsonString(eventRequestParameters);
852 } catch (final JsonProcessingException e) {
853 final String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + e;
854 LOGGER.error(message);
855 throw new PolicyEventException(message, e);
859 final ResponseEntity<StdPolicyResponse[]> result =
860 callNewPDP(SEND_EVENT_RESOURCE_NAME, HttpMethod.POST, body, StdPolicyResponse[].class);
862 return eventResult(result.getBody());
863 } catch (final Exception exception) {
864 final String defaulMessage = XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_INVALID_PDPS + pdps;
865 final String message = getErrorMessage(exception, defaulMessage, SEND_EVENT_RESOURCE_NAME);
866 LOGGER.error(message, exception);
867 throw new PolicyEventException(message, exception);
871 private String getErrorMessage(final Exception exception, final String defaulMessage, final String resource) {
872 final Throwable cause = exception.getCause();
873 if (cause != null && cause.getMessage().contains(UNAUTHORIZED_STATUS_CODE)) {
874 return XACMLErrorConstants.ERROR_PERMISSIONS + ERROR_AUTH_GET_PERM + resource;
876 if (cause != null && exception.getCause().getMessage().contains(BAD_REQUEST_STATUS_CODE)) {
877 return XACMLErrorConstants.ERROR_DATA_ISSUE + ERROR_DATA_ISSUE;
879 return defaulMessage;
882 private ArrayList<PolicyResponse> eventResult(final StdPolicyResponse[] response) {
883 final ArrayList<PolicyResponse> eventResult = new ArrayList<>();
884 if (response != null && response.length > 0) {
885 for (final StdPolicyResponse policyConfigResponse : response) {
886 eventResult.add(policyConfigResponse);
892 private void setProperty(final String propertyFilePath, String clientKey) throws PolicyEngineException {
893 if (propertyFilePath == null) {
894 throw new PolicyEngineException(
895 XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided");
897 final Properties prop = getProperties(propertyFilePath);
898 setProperty(prop, clientKey);
901 private void setProperty(final Properties properties, String clientKey) throws PolicyEngineException {
902 if (properties == null) {
903 throw new PolicyEngineException(
904 XACMLErrorConstants.ERROR_DATA_ISSUE + "NO properties provided, the value is NULL");
907 // UEB and DMAAP Settings
908 final String notificationTypeValue = properties.getProperty(NOTIFICATION_TYPE_PROP_NAME);
909 final String serverList = properties.getProperty(NOTIFICATION_SERVERS_PROP_NAME);
910 topic = properties.getProperty(NOTIFICATION_TOPIC_PROP_NAME);
911 apiKey = properties.getProperty(UEB_API_KEY_PROP_NAME);
912 apiSecret = properties.getProperty(UEB_API_SECRET_PROP_NAME);
914 setNotificationType(notificationTypeValue);
916 if (serverList == null) {
917 notificationType.clear();
918 notificationType.add(DEFAULT_NOTIFICATION);
920 "Properties file doesn't have the NOTIFICATION_SERVERS parameter system will use defualt websockets");
922 notificationURLList = getPropertyValueAsList(serverList.trim());
926 topic = topic.trim();
928 LOGGER.error("Properties file doesn't have the NOTIFICATION_TOPIC parameter.");
931 // Client ID Authorization Settings.
932 final String clientID = properties.getProperty(CLIENT_ID_PROP_NAME);
933 if (clientKey == null) {
934 clientKey = getClientKeyFromProperties(properties);
936 if (clientID == null || clientKey == null || clientID.isEmpty() || clientKey.isEmpty()) {
937 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
938 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
939 throw new PolicyEngineException(XACMLErrorConstants.ERROR_PERMISSIONS
940 + " Cannot proceed without the CLIENT_KEY and CLIENT_ID values !!");
942 setClientId(clientID.trim());
943 setClientKey(clientKey.trim());
945 setEnvironment(properties);
946 // Initializing the values.
948 readPdpProperites(properties);
949 // Get JUNIT property from properties file when running tests
950 checkJunit(properties);
953 private void readPdpProperites(final Properties prop) throws PolicyEngineException {
954 // Check the Keys for PDP_URLs
955 for (final String propertyKey : prop.stringPropertyNames()) {
956 if (propertyKey.startsWith(PDP_URL_PROP_NAME)) {
957 readPDPPropertyURL(prop, propertyKey);
960 if (pdps == null || pdps.isEmpty()) {
961 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
962 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
966 private void readPDPPropertyURL(Properties prop, String propertyKey) throws PolicyEngineException {
967 final String propertyValue = prop.getProperty(propertyKey);
968 if (propertyValue == null) {
969 throw new PolicyEngineException(
970 XACMLErrorConstants.ERROR_DATA_ISSUE + "Properties file doesn't have the PDP_URL parameter");
972 if (propertyValue.contains(SEMICOLLON)) {
973 final List<String> pdpDefault = Arrays.asList(propertyValue.split(REGEX));
974 for (final String pdpVal : pdpDefault) {
975 readPDPParam(pdpVal);
978 readPDPParam(propertyValue);
982 private void setNotificationType(final String propertyValue) {
983 if (propertyValue == null) {
984 notificationType.add(DEFAULT_NOTIFICATION);
986 "Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets");
988 notificationType = getPropertyValueAsList(propertyValue.trim());
992 private String getClientKeyFromProperties(final Properties prop) {
993 final String clientKeyValue = PeCryptoUtils.decrypt(prop.getProperty(CLIENT_KEY_PROP_NAME));
995 return PolicyUtils.decode(clientKeyValue);
996 } catch (UnsupportedEncodingException | IllegalArgumentException e) {
997 LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS
998 + " Cannot Decode the given Password Proceeding with given Password!!", e);
1000 return clientKeyValue;
1003 private Properties getProperties(final String propertyFilePath) throws PolicyEngineException {
1004 // Adding logic for remote Properties file.
1005 if (propertyFilePath.startsWith(HTTP)) {
1006 return getRemoteProperties(propertyFilePath);
1008 return getFileProperties(propertyFilePath);
1011 private Properties getFileProperties(final String propertyFilePath) throws PolicyEngineException {
1012 final Path file = Paths.get(propertyFilePath);
1013 if (!file.toFile().exists()) {
1014 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE
1015 + "File doesn't exist in the specified Path " + file.toString());
1017 if (file.toString().endsWith(".properties")) {
1018 try (BufferedReader bufferedReader = Files.newBufferedReader(file);) {
1019 final Properties prop = new Properties();
1020 prop.load(bufferedReader);
1022 } catch (final IOException exception) {
1023 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + exception);
1024 throw new PolicyEngineException(
1025 XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", exception);
1028 LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath);
1029 throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file");
1032 private Properties getRemoteProperties(final String propertyFilePath) throws PolicyEngineException {
1034 final URL configURL = new URL(propertyFilePath);
1035 final URLConnection connection = configURL.openConnection();
1036 final Properties prop = new Properties();
1037 prop.load(connection.getInputStream());
1039 } catch (final IOException e) {
1040 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1041 throw new PolicyEngineException(
1042 XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL " + e.getMessage());
1046 private List<String> getPropertyValueAsList(final String propertyValue) {
1047 if (propertyValue.contains(COMMA)) {
1048 return Arrays.asList(propertyValue.split(COMMA));
1050 final List<String> valuesList = new ArrayList<>();
1051 valuesList.add(propertyValue);
1055 private static void checkJunit(final Properties prop) {
1056 final String junitFlag = prop.getProperty(JUNIT_PROP_NAME);
1057 if (junitFlag == null || junitFlag.isEmpty()) {
1058 LOGGER.info("No JUNIT property provided, this will not be executed as a test.");
1060 if ("test".equalsIgnoreCase(junitFlag)) {
1061 StdPolicyEngine.junit = true;
1063 StdPolicyEngine.junit = false;
1068 private static void init() {
1069 pdps = new ArrayList<>();
1070 encoding = new ArrayList<>();
1073 private static void setEnvironment(final Properties prop) {
1074 environment = prop.getProperty(ENVIRONMENT_PROP_NAME, AAFEnvironment.DEVL.toString());
1075 if (environment.equalsIgnoreCase(AAFEnvironment.TEST.toString())) {
1076 environment = AAFEnvironment.TEST.toString();
1077 } else if (environment.equalsIgnoreCase(AAFEnvironment.PROD.toString())) {
1078 environment = AAFEnvironment.PROD.toString();
1080 environment = AAFEnvironment.DEVL.toString();
1084 private static void setClientId(final String clientID) {
1085 userName = clientID;
1089 * Read the PDP_URL parameter
1091 private void readPDPParam(final String pdpVal) throws PolicyEngineException {
1092 if (pdpVal.contains(COMMA)) {
1093 final List<String> pdpValues = Arrays.asList(pdpVal.split(PDP_VALUE_REGEX));
1094 if (pdpValues.size() == 3) {
1096 pdps.add(pdpValues.get(0));
1097 // 1:2 will be UserID:Password
1098 final String userID = pdpValues.get(1);
1099 final String userPas = PeCryptoUtils.decrypt(pdpValues.get(2));
1100 final Base64.Encoder encoder = Base64.getEncoder();
1101 encoding.add(encoder.encodeToString((userID + ":" + userPas).getBytes(StandardCharsets.UTF_8)));
1103 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues);
1104 throw new PolicyEngineException(
1105 XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues);
1109 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal);
1110 throw new PolicyEngineException(
1111 XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values.");
1116 * Allowing changes to the scheme and Handler.
1118 public void notification(final NotificationScheme scheme, final NotificationHandler handler) {
1119 this.scheme = scheme;
1120 this.handler = handler;
1121 LOGGER.debug("Scheme is : " + scheme.toString());
1122 LOGGER.debug("Handler is : " + handler.getClass().getName());
1124 if (UEB.equals(notificationType.get(0))) {
1125 if (this.uebThread) {
1126 AutoClientUEB.setAuto(scheme, handler);
1127 this.uebThread = registerUEBThread.isAlive();
1129 } else if (notificationType.get(0).equals(DMAAP)) {
1130 if (this.dmaapThread) {
1131 AutoClientDMAAP.setAuto(scheme, handler);
1132 this.dmaapThread = registerDMAAPThread.isAlive();
1135 AutoClientEnd.setAuto(scheme, handler);
1145 if (UEB.equals(notificationType.get(0)) && !this.uebThread) {
1146 this.uebClientThread = new AutoClientUEB(pdps.get(0), notificationURLList, apiKey, apiSecret);
1147 AutoClientUEB.setAuto(scheme, handler);
1148 this.registerUEBThread = new Thread(this.uebClientThread);
1149 this.registerUEBThread.start();
1150 this.uebThread = true;
1151 } else if (notificationType.get(0).equals(DMAAP) && !this.dmaapThread) {
1152 this.dmaapClientThread = new AutoClientDMAAP(notificationURLList, topic, userName, pass);
1153 AutoClientDMAAP.setAuto(scheme, handler);
1154 this.registerDMAAPThread = new Thread(this.dmaapClientThread);
1155 this.registerDMAAPThread.start();
1156 this.dmaapThread = true;
1158 if (pdps.get(0) != null) {
1159 if (AutoClientEnd.getUrl() == null) {
1160 AutoClientEnd.start(pdps.get(0));
1162 AutoClientEnd.stop();
1163 AutoClientEnd.start(pdps.get(0));
1170 * Gets the Notification if one exists. Used only for Manual Polling purposes.
1172 public PDPNotification getNotification() {
1173 // Check if there is proper scheme..
1174 PDPNotification notification;
1175 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)
1176 || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
1177 if (UEB.equals(notificationType.get(0))) {
1178 ManualClientEndUEB.start(pdps.get(0), notificationURLList, UNIQUEID);
1179 notification = ManualClientEndUEB.result(scheme);
1180 } else if (notificationType.get(0).equals(DMAAP)) {
1181 ManualClientEndDMAAP.start(notificationURLList, topic, UNIQUEID, userName, pass);
1182 notification = ManualClientEndDMAAP.result(scheme);
1184 ManualClientEnd.start(pdps.get(0));
1185 LOGGER.debug("manual notification requested.. : " + scheme.toString());
1186 notification = ManualClientEnd.result(scheme);
1188 if (notification == null) {
1189 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet..");
1192 return notification;
1198 * Setting the Scheme.
1200 public void setScheme(final NotificationScheme scheme) {
1201 this.scheme = scheme;
1202 if (UEB.equals(notificationType.get(0))) {
1203 AutoClientUEB.setScheme(this.scheme);
1204 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1205 ManualClientEndUEB.createTopic(pdps.get(0), UNIQUEID, notificationURLList);
1207 } else if (notificationType.get(0).equals(DMAAP)) {
1208 AutoClientDMAAP.setScheme(this.scheme);
1209 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)) {
1210 ManualClientEndDMAAP.createTopic(topic, UNIQUEID, notificationURLList, userName, pass);
1213 AutoClientEnd.setScheme(this.scheme);
1218 * Returns the Scheme
1220 public NotificationScheme getScheme() {
1225 * Returns the NotificationHandler
1227 public NotificationHandler getNotificationHandler() {
1228 return this.handler;
1232 * Stop the Notification Service if its running.
1234 public void stopNotification() {
1235 if (this.scheme != null && this.handler != null
1236 && (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)
1237 || this.scheme.equals(NotificationScheme.AUTO_NOTIFICATIONS))) {
1238 LOGGER.info("Clear Notification called.. ");
1239 if (UEB.equals(notificationType.get(0))) {
1240 this.uebClientThread.terminate();
1241 this.uebThread = false;
1242 } else if (notificationType.get(0).equals(DMAAP)) {
1243 this.dmaapClientThread.terminate();
1244 this.dmaapThread = false;
1246 AutoClientEnd.stop();
1252 * Push a policy to the PDP API implementation
1254 public String pushPolicy(final String policyScope, final String policyName, final String policyType,
1255 final String pdpGroup, final UUID requestID) throws PolicyException {
1256 validateParameters(policyName, policyScope);
1258 final PushPolicyParameters pushPolicyParameters = new PushPolicyParameters();
1259 pushPolicyParameters.setPolicyName(policyScope + "." + policyName);
1260 pushPolicyParameters.setPolicyType(policyType);
1261 pushPolicyParameters.setPdpGroup(pdpGroup);
1262 pushPolicyParameters.setRequestID(requestID);
1263 return pushPolicyImpl(pushPolicyParameters).getResponseMessage();
1266 private boolean isNotValid(final String value) {
1267 return value == null || value.trim().isEmpty();
1270 public String createUpdateConfigPolicy(final String policyName, final String policyDescription,
1271 final String onapName, final String configName, final Map<String, String> configAttributes,
1272 final String configType, final String body, final String policyScope, final UUID requestID,
1273 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1274 final boolean updateFlag) throws PolicyException {
1275 return createUpdateConfigPolicyImpl(policyName, policyDescription, onapName, configName, configAttributes,
1276 configType, body, policyScope, requestID, riskLevel, riskType, guard, ttlDate, updateFlag);
1280 * Create Config Policy API Implementation
1282 private String createUpdateConfigPolicyImpl(final String policyName, final String policyDescription,
1283 final String onapName, final String configName, final Map<String, String> configAttributes,
1284 final String configType, final String body, final String policyScope, final UUID requestID,
1285 final String riskLevel, final String riskType, final String guard, final String ttlDate,
1286 final boolean updateFlag) throws PolicyException {
1288 validateParameters(policyName, policyScope);
1290 final PolicyParameters policyParameters = new PolicyParameters();
1291 policyParameters.setPolicyClass(PolicyClass.Config);
1292 policyParameters.setPolicyConfigType(PolicyConfigType.Base);
1293 policyParameters.setPolicyName(policyScope + "." + policyName);
1294 policyParameters.setPolicyDescription(policyDescription);
1295 policyParameters.setOnapName(onapName);
1296 policyParameters.setConfigName(configName);
1298 final Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
1299 attributes.put(AttributeType.MATCHING, configAttributes);
1301 policyParameters.setAttributes(attributes);
1302 policyParameters.setConfigBodyType(PolicyType.valueOf(configType));
1303 policyParameters.setConfigBody(body);
1304 policyParameters.setRequestID(requestID);
1305 policyParameters.setRiskLevel(riskLevel);
1306 policyParameters.setRiskType(riskType);
1307 policyParameters.setGuard(Boolean.parseBoolean(guard));
1308 policyParameters.setTtlDate(toDate(ttlDate));
1309 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1312 private Date toDate(final String dateString) {
1314 return new SimpleDateFormat(DATE_FORMAT).parse(dateString);
1315 } catch (final ParseException e) {
1316 LOGGER.warn("Error Parsing date given " + dateString);
1321 public String createUpdateConfigFirewallPolicy(final String policyName, final JsonObject firewallJson,
1322 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1323 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1324 return createUpdateConfigFirewallPolicyImpl(policyName, firewallJson, policyScope, requestID, riskLevel,
1325 riskType, guard, ttlDate, updateFlag);
1329 * Create Update Config Firewall Policy API implementation
1331 private String createUpdateConfigFirewallPolicyImpl(final String policyName, final JsonObject firewallJson,
1332 final String policyScope, final UUID requestID, final String riskLevel, final String riskType,
1333 final String guard, final String ttlDate, final boolean updateFlag) throws PolicyException {
1334 validateParameters(policyName, policyScope);
1336 final PolicyParameters policyParameters = new PolicyParameters();
1337 policyParameters.setPolicyClass(PolicyClass.Config);
1338 policyParameters.setPolicyConfigType(PolicyConfigType.Firewall);
1339 policyParameters.setPolicyName(policyScope + "." + policyName);
1340 policyParameters.setConfigBody(firewallJson.toString());
1341 policyParameters.setRequestID(requestID);
1342 policyParameters.setRiskLevel(riskLevel);
1343 policyParameters.setRiskType(riskType);
1344 policyParameters.setGuard(Boolean.parseBoolean(guard));
1345 policyParameters.setTtlDate(toDate(ttlDate));
1346 return createUpdatePolicyImpl(policyParameters, updateFlag).getResponseMessage();
1349 private void validateParameters(final String policyName, final String policyScope) throws PolicyException {
1350 if (isNotValid(policyScope)) {
1351 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
1352 LOGGER.error(message);
1353 throw new PolicyException(message);
1355 if (isNotValid(policyName)) {
1356 final String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
1357 LOGGER.error(message);
1358 throw new PolicyException(message);
1362 public static void setClientKey(final String clientKey) {
1363 if (clientKey != null && !clientKey.isEmpty()) {
1364 StdPolicyEngine.pass = clientKey;
1365 setClientEncoding();
1370 * Get the Environment.
1372 public static String getEnvironment() {
1377 * Rotate the PDP list upon WEBsocket Failures
1379 public static void rotatePDPList() {
1380 Collections.rotate(pdps, -1);
1381 Collections.rotate(encoding, -1);
1385 * Get the latest PDP
1387 public static String getPDPURL() {
1397 List<String> getNotificationType() {
1398 return notificationType;
1402 List<String> getNotificationURLList() {
1403 return notificationURLList;