2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
22 package org.openecomp.policy.std;
24 import java.io.ByteArrayInputStream;
26 import java.io.FileInputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30 import java.io.StringReader;
31 import java.net.HttpURLConnection;
32 import java.net.MalformedURLException;
35 import java.net.URLConnection;
36 import java.nio.charset.StandardCharsets;
37 import java.nio.file.Files;
38 import java.nio.file.Path;
39 import java.nio.file.Paths;
40 import java.text.SimpleDateFormat;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.Base64;
44 import java.util.Collection;
45 import java.util.Collections;
46 import java.util.Date;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.List;
51 import java.util.Properties;
52 import java.util.UUID;
54 import javax.json.Json;
55 import javax.json.JsonArrayBuilder;
56 import javax.json.JsonObject;
57 import javax.json.JsonObjectBuilder;
58 import javax.json.JsonReader;
59 import javax.xml.parsers.DocumentBuilder;
60 import javax.xml.parsers.DocumentBuilderFactory;
61 import javax.xml.parsers.ParserConfigurationException;
63 import org.apache.commons.io.IOUtils;
64 import org.apache.http.entity.ContentType;
65 //import org.apache.log4j.Logger;
66 import org.json.JSONObject;
67 import org.openecomp.policy.api.AttributeType;
68 import org.openecomp.policy.api.ConfigRequestParameters;
69 import org.openecomp.policy.api.DecisionRequestParameters;
70 import org.openecomp.policy.api.DecisionResponse;
71 import org.openecomp.policy.api.DeletePolicyParameters;
72 import org.openecomp.policy.api.DictionaryParameters;
73 import org.openecomp.policy.api.EventRequestParameters;
74 import org.openecomp.policy.api.ImportParameters;
75 import org.openecomp.policy.api.NotificationHandler;
76 import org.openecomp.policy.api.NotificationScheme;
77 import org.openecomp.policy.api.PDPNotification;
78 import org.openecomp.policy.api.PolicyChangeResponse;
79 import org.openecomp.policy.api.PolicyClass;
80 import org.openecomp.policy.api.PolicyConfig;
81 import org.openecomp.policy.api.PolicyConfigException;
82 import org.openecomp.policy.api.PolicyConfigStatus;
83 import org.openecomp.policy.api.PolicyConfigType;
84 import org.openecomp.policy.api.PolicyDecision;
85 import org.openecomp.policy.api.PolicyDecisionException;
86 import org.openecomp.policy.api.PolicyEngineException;
87 import org.openecomp.policy.api.PolicyEventException;
88 import org.openecomp.policy.api.PolicyParameters;
89 import org.openecomp.policy.api.PolicyResponse;
90 import org.openecomp.policy.api.PolicyResponseStatus;
91 import org.openecomp.policy.api.PolicyType;
92 import org.openecomp.policy.api.PushPolicyParameters;
93 import org.openecomp.policy.api.RuleProvider;
94 //import org.openecomp.policy.utils.AAFPolicyClient;
95 //import org.openecomp.policy.utils.AAFPolicyException;
96 import org.w3c.dom.Document;
97 import org.xml.sax.SAXException;
99 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
100 import org.openecomp.policy.common.logging.flexlogger.Logger;
102 import com.att.research.xacml.api.Advice;
103 import com.att.research.xacml.api.AttributeAssignment;
104 import com.att.research.xacml.api.Decision;
105 import com.att.research.xacml.api.Obligation;
106 import com.att.research.xacml.api.Request;
107 import com.att.research.xacml.api.Response;
108 import com.att.research.xacml.api.Result;
109 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
110 import org.openecomp.policy.xacml.std.pap.StdPAPPolicy;
111 import org.openecomp.policy.xacml.std.pap.StdPDPPolicy;
113 import com.att.research.xacml.api.pap.PAPException;
114 import com.att.research.xacml.api.pap.PDPPolicy;
115 import com.att.research.xacml.std.json.JSONRequest;
116 import com.att.research.xacml.std.json.JSONResponse;
117 import com.fasterxml.jackson.databind.ObjectMapper;
118 import com.google.common.base.CharMatcher;
123 * PolicyEngine Implementation class
127 public class StdPolicyEngine {
128 // Change the default Priority value here.
129 private static final int defaultPriority = 9999;
131 private String propertyFilePath = null;
132 private static List<String> pdps = null;
133 private static List<String> paps = null;
134 private static String environment= null;
135 private static String userName = null;
136 private static String pass = null;
137 private static List<String> encoding = null;
138 private static List<String> encodingPAP = null;
139 private List<String> pdp_default = null;
140 private List<String> pap_default = null;
141 private List<String> type_default = null;
142 private List<String> notificationType = new ArrayList<String>();
143 private List<String> uebURLList = new ArrayList<String>();
144 private NotificationScheme scheme = null;
145 private NotificationHandler handler = null;
146 private Matches match = null;
147 private Boolean decide = false;
148 private AutoClientUEB UEBClientThread = null;
149 private Thread registerUEBThread = null;
150 private boolean UEBThread = false;
151 private String policyId = null;
152 private String description = null;
153 private String pushVersion = null;
154 private boolean isValid = false;
155 private int responseCode = 0;
156 private boolean unique = false;
157 private boolean junit = false;
158 //private AAFPolicyClient aafClient = null;
160 private String pyPDPClientFile = null;
162 final private static String uniqueID = UUID.randomUUID ().toString ();
164 private static Logger logger = FlexLogger.getLogger(StdPolicyConfig.class.getName());
167 * Taking the Property file even if it null.
169 public StdPolicyEngine(String propertyFilePath)
170 throws PolicyEngineException {
171 setProperty(propertyFilePath);
175 * Taking the Notification Constructor.
177 public StdPolicyEngine(String propertyFilePath, NotificationScheme scheme,
178 NotificationHandler handler) throws PolicyEngineException {
179 setProperty(propertyFilePath);
180 this.scheme = scheme;
181 this.handler = handler;
182 if (!notificationType.get(0).equals("ueb")){
183 AutoClientEnd.setAuto(scheme, handler);
185 notification(scheme, handler);
189 * Taking the Notification Constructor.
191 public StdPolicyEngine(String propertyFilePath, NotificationScheme scheme)
192 throws PolicyEngineException {
193 setProperty(propertyFilePath);
194 this.scheme = scheme;
198 // This Call will be used by PyPDP Requests
199 public StdPolicyEngine(List<String> configURL, List<String> configPapURL, List<String> encodingPAP, List<String> encoding, NotificationScheme scheme, NotificationHandler handler, String environment, String clientProperties, Boolean isTest) {
200 StdPolicyEngine.pdps = configURL;
201 StdPolicyEngine.paps = configPapURL;
202 StdPolicyEngine.encoding = encoding;
203 StdPolicyEngine.encodingPAP = encodingPAP;
204 StdPolicyEngine.environment = environment;
205 Properties props = new Properties();
206 props.setProperty("ENVIRONMENT", environment);
207 //Not Supported for 1610 Open Source
209 aafClient = AAFPolicyClient.getInstance(props);
210 } catch (AAFPolicyException e) {
211 logger.error(XACMLErrorConstants.ERROR_UNKNOWN + e.getMessage());
213 pyPDPClientFile = clientProperties;
214 // Default Notification Type for PyPDPServers.
215 notificationType.add("websocket");
217 notification(scheme, handler);
222 * sendEvent API Implementation
224 public Collection<PolicyResponse> event(Map<String, String> eventAttributes, UUID requestID)
225 throws PolicyEventException {
226 Collection<PolicyResponse> policyResponse = null;
227 policyResponse = event(eventAttributes, requestID, userName, pass);
228 return policyResponse;
232 * sendEvent API Implementation for eventRequestParameters
234 public Collection<PolicyResponse> event(EventRequestParameters eventRequestParameters) throws PolicyEventException{
235 Collection<PolicyResponse> response = event(eventRequestParameters.getEventAttributes(), eventRequestParameters.getRequestID());
240 * getConfig API Implementation
242 public Collection<PolicyConfig> config(String eCOMPComponentName,
243 String configName, Map<String, String> configAttributes, UUID requestID)
244 throws PolicyConfigException {
245 Collection<PolicyConfig> policyConfig = null;
246 policyConfig = config(eCOMPComponentName, configName, configAttributes, requestID, userName, pass);
251 * getConfig API Implementation
253 public Collection<PolicyConfig> config(String eCOMPComponentName,
254 String configName, UUID requestID) throws PolicyConfigException {
255 Collection<PolicyConfig> policyConfig = null;
256 policyConfig = config(eCOMPComponentName, configName,null, requestID, userName, pass);
261 * getConfig API Implementation
263 public Collection<PolicyConfig> config(String eCOMPComponentName, UUID requestID)
264 throws PolicyConfigException {
265 Collection<PolicyConfig> policyConfig = null;
266 policyConfig = config(eCOMPComponentName, requestID, userName, pass);
271 * getConfig using the PolicyFileName Implementation
273 public Collection<PolicyConfig> policyName(String policyName, UUID requestID)
274 throws PolicyConfigException {
275 Collection<PolicyConfig> policyConfig = null;
276 policyConfig = configPolicyName(policyName, requestID, userName, pass);
281 * getConfig using configRequestParameters Implementation
283 public Collection<PolicyConfig> config(ConfigRequestParameters configRequestParameters) throws PolicyConfigException{
284 Collection<PolicyConfig> response = null;
285 response = configRequest(configRequestParameters, userName, pass);
290 * listPolicies using configRequestParameters Implementation
292 public Collection<String> listConfig(ConfigRequestParameters listPolicyRequestParameters) throws PolicyConfigException{
293 Collection<String> policyList = new ArrayList<String>();
294 policyList = listConfigRequest(listPolicyRequestParameters, userName, pass);
299 * getDecision using the decision Attributes.
301 public DecisionResponse decide(String eCOMPComponentName,
302 Map<String, String> decisionAttributes, UUID requestID)
303 throws PolicyDecisionException {
304 DecisionResponse policyDecision = policyDecide(eCOMPComponentName,
305 decisionAttributes, requestID, userName, pass);
306 return policyDecision;
310 * getDecision Using decisionRequestParameters.
312 public DecisionResponse decide(DecisionRequestParameters decisionRequestParameters) throws PolicyDecisionException{
313 DecisionResponse decision = decide(decisionRequestParameters.getECOMPComponentName(), decisionRequestParameters.getDecisionAttributes(), decisionRequestParameters.getRequestID());
318 * PushPolicy using pushPolicyParameters.
320 public PolicyChangeResponse pushPolicy(PushPolicyParameters pushPolicyParameters) throws Exception{
321 return pushPolicy(pushPolicyParameters, userName, pass);
324 public PolicyChangeResponse pushPolicy(PushPolicyParameters pushPolicyParameters, String userID, String passcode) throws Exception{
325 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
326 String resource= "pushPolicy";
327 if(!checkPermissions(userID, passcode, resource)){
328 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
329 response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
330 response.setResponseCode(401);
333 String plainName = null;
336 if(pushPolicyParameters.getPolicyName()!=null){
337 plainName = pushPolicyParameters.getPolicyName().substring(pushPolicyParameters.getPolicyName().lastIndexOf(".")+1, pushPolicyParameters.getPolicyName().length());
338 scope = pushPolicyParameters.getPolicyName().substring(0, pushPolicyParameters.getPolicyName().lastIndexOf("."));
339 logger.info("Name is "+ plainName +" scope is "+ scope);
342 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
343 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
346 // check incoming requestID, if null then generate one here so the same id can be used for the multiple transactions for the same Push Policy request (i.e. POST, PUT)
347 UUID requestID = pushPolicyParameters.getRequestID();
348 if (requestID == null) {
349 requestID = UUID.randomUUID();
350 logger.info("Request ID was not provided from input, so sending generated ID: " + requestID.toString());
352 logger.info("Request ID was provided from input: " + requestID.toString());
354 // now use the local requestID field derived above to pass to the rest of the Push Policy process (below)
355 // response.setResponseMessage(pushPolicy(scope, plainName, pushPolicyParameters.getPolicyType(), pushPolicyParameters.getPdpGroup(), pushPolicyParameters.getRequestID()));
356 response.setResponseMessage(pushPolicy(scope, plainName, pushPolicyParameters.getPolicyType(), pushPolicyParameters.getPdpGroup(), requestID));
357 response.setResponseCode(responseCode);
362 * Delete a Policy using deletePolicyParameters
364 public PolicyChangeResponse deletePolicy(DeletePolicyParameters parameters) throws Exception {
365 return deletePolicy(parameters, userName, pass);
368 public PolicyChangeResponse deletePolicy(DeletePolicyParameters parameters, String userID,String passcode) throws Exception {
369 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
370 String resource= "deletePolicy";
371 if(!checkPermissions(userID, passcode, resource)){
372 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
373 response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
374 response.setResponseCode(401);
377 if (parameters.getPolicyComponent()!=null) {
378 if (parameters.getPolicyComponent().equalsIgnoreCase("PAP")) {
379 response.setResponseMessage(deletePolicyFromPAP(parameters));
380 } else if (parameters.getPolicyComponent().equalsIgnoreCase("PDP")) {
381 response.setResponseMessage(deletePolicyFromPDP(parameters));
383 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist.");
384 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Component does not exist. Please enter either PAP or PDP to delete the policy from a specified Policy Component.");
387 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given.");
388 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Component given.");
391 response.setResponseCode(responseCode);
396 * createDictionaryItem using dictionaryParameters.
398 public PolicyChangeResponse createDictionaryItem(DictionaryParameters parameters) throws Exception{
399 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
401 if(parameters.getDictionaryType()!=null || parameters.getDictionaryType().equals("")){
402 if(parameters.getDictionary()!=null || parameters.getDictionary().equals("")){
403 if(parameters.getDictionaryFields()!=null){
404 logger.info("Parameters are good... start create dictionary item API...");
406 Map<String,String> dictionaryFields = parameters.getDictionaryFields().get(AttributeType.DICTIONARY);
408 StdPAPPolicy newDictionaryItem = new StdPAPPolicy(parameters.getDictionaryType().toString(), parameters.getDictionary(), dictionaryFields);
410 String result = (String) callPAP(newDictionaryItem, new String[] {"operation=createDictionary", "apiflag=dictionaryApi"}, parameters.getRequestID(), "dictionaryItem");
412 response.setResponseCode(responseCode);
413 response.setResponseMessage(result);
416 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Fields given.");
417 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Fields given.");
420 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given.");
421 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary given.");
424 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given.");
425 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Dictionary Type given.");
437 * createPolicy Using policyParameters.
439 public PolicyChangeResponse createPolicy(PolicyParameters policyParameters) throws Exception{
440 return createPolicy(policyParameters, userName, pass);
443 public PolicyChangeResponse createPolicy(PolicyParameters policyParameters, String userID, String passcode) throws Exception{
444 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
445 String resource= "createPolicy";
446 if(!checkPermissions(userID, passcode, resource)){
447 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
448 response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
449 response.setResponseCode(401);
452 String plainName = null;
455 if (policyParameters.getTtlDate()!=null){
456 date = ConvertDate(policyParameters.getTtlDate());
459 if(policyParameters.getPolicyName()!=null){
460 plainName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf(".")+1, policyParameters.getPolicyName().length());
461 scope = policyParameters.getPolicyName().substring(0, policyParameters.getPolicyName().lastIndexOf("."));
462 logger.info("Name is "+ plainName +" scope is "+ scope);
465 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
466 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
468 if(policyParameters.getPolicyConfigType()!=null){
469 // This is Config Class Policy.
471 if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.Firewall)){
472 if(policyParameters.getConfigBody()!=null){
473 JsonObject json = null;
475 json = stringToJsonObject(policyParameters.getConfigBody());
477 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
478 logger.error(message);
479 throw new Exception(message);
481 response.setResponseMessage(createConfigFirewallPolicy(plainName, json, scope, policyParameters.getRequestID(), userID, passcode,
482 policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
484 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
485 logger.error(message);
486 response.setResponseMessage(message);
490 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.Base)){
491 if(policyParameters.getConfigBody()!=null) {
492 if(policyParameters.getConfigBodyType()!=null){
493 response.setResponseMessage(createConfigPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getConfigName(),
494 policyParameters.getAttributes().get(AttributeType.MATCHING), policyParameters.getConfigBodyType().toString(), policyParameters.getConfigBody(), scope, policyParameters.getRequestID(), userID, passcode,
495 policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
497 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body Type given.";
498 logger.error(message);
499 response.setResponseMessage(message);
502 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
503 logger.error(message);
504 response.setResponseMessage(message);
508 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.BRMS_RAW)){
509 if(policyParameters.getConfigBody()!=null){
511 /*public String createUpdateBRMSRawPolicy(String policyName, String policyDescription, Map<String,String> dyanamicFieldConfigAttributes,
512 * String brmsRawBody, String policyScope, Boolean isEdit, UUID requestID)*/
513 response.setResponseMessage(createUpdateBRMSRawPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
514 policyParameters.getConfigBody(),scope, false,
515 policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()),
518 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
519 logger.error(message);
520 throw new Exception(message);
524 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.BRMS_PARAM)){
525 if(policyParameters.getConfigBody()!=null){
527 response.setResponseMessage(createUpdateBRMSParamPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
528 policyParameters.getConfigBody(),scope, false,
529 policyParameters.getRequestID(),policyParameters.getAttributes(),policyParameters.getRiskLevel(), policyParameters.getRiskType(),
530 String.valueOf(policyParameters.getGuard()), date));
532 response.setResponseMessage(createUpdateBRMSParamPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
534 policyParameters.getRequestID(),policyParameters.getAttributes(),policyParameters.getRiskLevel(), policyParameters.getRiskType(),
535 String.valueOf(policyParameters.getGuard()), date));
538 // Micro Services Policy
539 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.MicroService)){
540 if(policyParameters.getConfigBody()!=null){
541 JsonObject json = null;
543 json = stringToJsonObject(policyParameters.getConfigBody());
545 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
546 logger.error(message);
547 throw new Exception(message);
549 //call Micro Services Create API here
550 response.setResponseMessage(createUpdateMicroServicesPolicy(plainName, json, policyParameters.getEcompName(),
551 scope, false, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(),
552 String.valueOf(policyParameters.getGuard()), date));
555 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Micro Service or Attributes Config Body Present";
556 logger.error(message);
557 throw new Exception(message);
560 // ClosedLoop_Fault Policy
561 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.ClosedLoop_Fault)){
562 if(policyParameters.getConfigBody()!=null){
563 JsonObject json = null;
565 if(validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
566 json = stringToJsonObject(policyParameters.getConfigBody());
568 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "The ClosedLoop JSON Contains Non ASCII Characters.";
569 logger.error(message);
570 response.setResponseCode(400);
571 response.setResponseMessage(message);
576 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
577 logger.error(message);
578 response.setResponseCode(400);
579 response.setResponseMessage(message);
583 //call ClosedLoop_Fault Create API here
584 response.setResponseMessage(createUpdateClosedLoopPolicy(plainName, json, policyParameters.getPolicyDescription(),
585 scope, false, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(),
586 String.valueOf(policyParameters.getGuard()), date));
589 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
590 logger.error(message);
591 response.setResponseMessage(message);
592 response.setResponseCode(400);
596 // ClosedLoop_PM Policy
597 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.ClosedLoop_PM)){
598 if(policyParameters.getConfigBody()!=null){
599 JsonObject json = null;
601 if(validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
602 json = stringToJsonObject(policyParameters.getConfigBody());
604 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "The ClosedLoop PM JSON Contains Non ASCII Characters.";
605 logger.error(message);
606 response.setResponseMessage(message);
607 response.setResponseCode(400);
613 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
614 logger.error(message);
615 response.setResponseMessage(message);
616 response.setResponseCode(400);
620 //call ClosedLoop_Fault Create API here
621 response.setResponseMessage(createUpdateClosedLoopPmPolicy(plainName, json, policyParameters.getPolicyDescription(),
622 scope, false, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(),
623 String.valueOf(policyParameters.getGuard()), date));
626 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
627 logger.error(message);
628 response.setResponseMessage(message);
629 response.setResponseCode(400);
635 } else if (policyParameters.getPolicyClass()!=null){
636 if(policyParameters.getPolicyClass().equals(PolicyClass.Action)){
637 // call Action Create API here.
638 response.setResponseMessage(createUpdateActionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getAttributes().get(AttributeType.MATCHING),
639 policyParameters.getDynamicRuleAlgorithmLabels(), policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
640 policyParameters.getActionPerformer(), policyParameters.getActionAttribute(), scope, false, policyParameters.getRequestID()));
641 }else if(policyParameters.getPolicyClass().equals(PolicyClass.Decision)){
642 // Call Decision Create API here.
643 if (policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)) {
644 response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
645 policyParameters.getAttributes().get(AttributeType.MATCHING), policyParameters.getAttributes().get(AttributeType.SETTINGS), policyParameters.getDynamicRuleAlgorithmLabels(),
646 policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
647 scope, false, policyParameters.getRequestID()));
648 }else if(policyParameters.getAttributes()!=null && !policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
649 response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
650 null, policyParameters.getAttributes().get(AttributeType.SETTINGS), policyParameters.getDynamicRuleAlgorithmLabels(),
651 policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
652 scope, false, policyParameters.getRequestID()));
653 }else if(policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && !policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
654 response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
655 policyParameters.getAttributes().get(AttributeType.MATCHING), null, policyParameters.getDynamicRuleAlgorithmLabels(),
656 policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
657 scope, false, policyParameters.getRequestID()));
659 response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
660 null, null, policyParameters.getDynamicRuleAlgorithmLabels(),
661 policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
662 scope, false, policyParameters.getRequestID()));
666 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Class found.");
667 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Class found.");
669 response.setResponseCode(responseCode);
674 * updatePolicy using policyParameters.
676 public PolicyChangeResponse updatePolicy(PolicyParameters policyParameters) throws Exception{
677 return updatePolicy(policyParameters, userName, pass);
680 public PolicyChangeResponse updatePolicy(PolicyParameters policyParameters,String userID, String passcode) throws Exception{
681 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
682 String resource= "updatePolicy";
683 if(!checkPermissions(userID, passcode, resource)){
684 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
685 response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
686 response.setResponseCode(401);
689 String plainName = null;
692 if (policyParameters.getTtlDate()!=null){
693 date = ConvertDate(policyParameters.getTtlDate());
696 if(policyParameters.getPolicyName()!=null){
697 plainName = policyParameters.getPolicyName().substring(policyParameters.getPolicyName().lastIndexOf(".")+1, policyParameters.getPolicyName().length());
698 scope = policyParameters.getPolicyName().substring(0, policyParameters.getPolicyName().lastIndexOf("."));
699 logger.info("Name is "+ plainName +" scope is "+ scope);
702 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
703 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
705 if(policyParameters.getPolicyConfigType()!=null){
706 // This is Config Class Policy.
708 if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.Firewall)){
709 if(policyParameters.getConfigBody()!=null){
710 JsonObject json = null;
712 json = stringToJsonObject(policyParameters.getConfigBody());
714 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
715 logger.error(message);
716 throw new Exception(message);
718 response.setResponseMessage(updateConfigFirewallPolicy(plainName, json, scope, policyParameters.getRequestID(), userID, passcode,policyParameters.getRiskLevel(),
719 policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
721 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
722 logger.error(message);
723 response.setResponseMessage(message);
727 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.Base)){
728 if(policyParameters.getConfigBody()!=null) {
729 if(policyParameters.getConfigBodyType()!=null){
730 response.setResponseMessage(updateConfigPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getConfigName(),
731 policyParameters.getAttributes().get(AttributeType.MATCHING), policyParameters.getConfigBodyType().toString(), policyParameters.getConfigBody(), scope,
732 policyParameters.getRequestID(), userID, passcode, policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
734 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body Type given.";
735 logger.error(message);
736 response.setResponseMessage(message);
739 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Config Body given.";
740 logger.error(message);
741 response.setResponseMessage(message);
745 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.BRMS_RAW)){
746 if(policyParameters.getConfigBody()!=null){
747 /*public String createUpdateBRMSRawPolicy(String policyName, String policyDescription, Map<String,String> dyanamicFieldConfigAttributes,
748 * String brmsRawBody, String policyScope, Boolean isEdit, UUID requestID)*/
749 response.setResponseMessage(createUpdateBRMSRawPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
750 policyParameters.getConfigBody(),scope, true,
751 policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
753 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
754 logger.error(message);
755 throw new Exception(message);
759 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.BRMS_PARAM)){
760 if(policyParameters.getConfigBody()!=null){
762 /* public String createUpdateBRMSParamPolicy(String policyName, String policyDescription, Map<AttributeType, Map<String, String>> dyanamicFieldConfigAttributes,
763 String brmsRawBody, String policyScope, Boolean isEdit,
764 UUID requestID,Map<String,String> drlRuleAndUIParams)*/
765 response.setResponseMessage(createUpdateBRMSParamPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
766 policyParameters.getConfigBody(),scope, true,
767 policyParameters.getRequestID(),policyParameters.getAttributes(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
769 response.setResponseMessage(createUpdateBRMSParamPolicy(plainName, policyParameters.getPolicyDescription(),policyParameters.getAttributes(),
771 policyParameters.getRequestID(),policyParameters.getAttributes(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
774 // Micro Services Policy
775 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.MicroService)){
776 if(policyParameters.getConfigBody()!=null){
777 JsonObject json = null;
779 json = stringToJsonObject(policyParameters.getConfigBody());
781 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
782 logger.error(message);
783 throw new Exception(message);
785 //call Micro Services Create API here
786 response.setResponseMessage(createUpdateMicroServicesPolicy(plainName, json, policyParameters.getEcompName(),
787 scope, true, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
790 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Micro Service or Attributes Config Body Present";
791 logger.error(message);
792 throw new Exception(message);
795 // ClosedLoop_Fault Policy
796 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.ClosedLoop_Fault)){
797 if(policyParameters.getConfigBody()!=null){
798 JsonObject json = null;
800 if(validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
801 json = stringToJsonObject(policyParameters.getConfigBody());
803 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "The ClosedLoop JSON Contains Non ASCII Characters.";
804 logger.error(message);
805 response.setResponseMessage(message);
810 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
811 logger.error(message);
812 response.setResponseMessage(message);
815 //call ClosedLoop_Fault Create API here
816 response.setResponseMessage(createUpdateClosedLoopPolicy(plainName, json, policyParameters.getPolicyDescription(),
817 scope, true, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(), String.valueOf(policyParameters.getGuard()), date));
820 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
821 logger.error(message);
822 response.setResponseMessage(message);
825 // ClosedLoop_PM Policy
826 else if(policyParameters.getPolicyConfigType().equals(PolicyConfigType.ClosedLoop_PM)){
827 if(policyParameters.getConfigBody()!=null){
828 JsonObject json = null;
830 if(validateNONASCIICharactersAndAllowSpaces(policyParameters.getConfigBody())){
831 json = stringToJsonObject(policyParameters.getConfigBody());
833 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ "The ClosedLoop PM JSON Contains Non ASCII Characters.";
834 logger.error(message);
835 response.setResponseMessage(message);
840 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " improper JSON object : " + policyParameters.getConfigBody();
841 logger.error(message);
842 response.setResponseMessage(message);
845 //call ClosedLoop_Fault Create API here
846 response.setResponseMessage(createUpdateClosedLoopPmPolicy(plainName, json, policyParameters.getPolicyDescription(),
847 scope, true, policyParameters.getRequestID(),policyParameters.getRiskLevel(), policyParameters.getRiskType(),
848 String.valueOf(policyParameters.getGuard()), date));
851 String message = XACMLErrorConstants.ERROR_DATA_ISSUE+ " No Config Body Present";
852 logger.error(message);
853 response.setResponseMessage(message);
859 if(policyParameters.getPolicyClass().equals(PolicyClass.Action)){
860 // call Action Update API here.
861 response.setResponseMessage(createUpdateActionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getAttributes().get(AttributeType.MATCHING),
862 policyParameters.getDynamicRuleAlgorithmLabels(), policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
863 policyParameters.getActionPerformer(), policyParameters.getActionAttribute(), scope, true, policyParameters.getRequestID()));
865 }else if(policyParameters.getPolicyClass().equals(PolicyClass.Decision)){
866 // Call Decision Create API here.
867 if (policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)) {
868 response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
869 policyParameters.getAttributes().get(AttributeType.MATCHING), policyParameters.getAttributes().get(AttributeType.SETTINGS), policyParameters.getDynamicRuleAlgorithmLabels(),
870 policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
871 scope, true, policyParameters.getRequestID()));
872 }else if(policyParameters.getAttributes()!=null && !policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
873 response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
874 null, policyParameters.getAttributes().get(AttributeType.SETTINGS), policyParameters.getDynamicRuleAlgorithmLabels(),
875 policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
876 scope, true, policyParameters.getRequestID()));
877 }else if(policyParameters.getAttributes()!=null && policyParameters.getAttributes().containsKey(AttributeType.MATCHING) && !policyParameters.getAttributes().containsKey(AttributeType.SETTINGS)){
878 response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
879 policyParameters.getAttributes().get(AttributeType.MATCHING), null, policyParameters.getDynamicRuleAlgorithmLabels(),
880 policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
881 scope, true, policyParameters.getRequestID()));
883 response.setResponseMessage(createUpdateDecisionPolicy(plainName, policyParameters.getPolicyDescription(), policyParameters.getEcompName(), policyParameters.getRuleProvider(),
884 null, null, policyParameters.getDynamicRuleAlgorithmLabels(),
885 policyParameters.getDynamicRuleAlgorithmField1(), policyParameters.getDynamicRuleAlgorithmFunctions(), policyParameters.getDynamicRuleAlgorithmField2(),
886 scope, true, policyParameters.getRequestID()));
890 response.setResponseCode(responseCode);
894 public DecisionResponse policyDecide(String eCOMPComponentName,
895 Map<String, String> decisionAttributes, UUID requestID, String userID, String passcode)
896 throws PolicyDecisionException {
897 String resource= "getDecision";
898 if(!checkPermissions(userID, passcode, resource)){
899 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
900 throw new PolicyDecisionException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
902 DecisionResponse policyDecision;
903 if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) {
904 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName);
905 throw new PolicyDecisionException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given.");
907 if (decisionAttributes != null && !decisionAttributes.isEmpty()) {
908 JsonArrayBuilder resourceArray = Json.createArrayBuilder();
909 for (String key : decisionAttributes.keySet()) {
911 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key");
912 throw new PolicyDecisionException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an empty Key");
914 JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
915 if (decisionAttributes.get(key).matches("[0-9]+")) {
916 int val = Integer.parseInt(decisionAttributes.get(key));
917 resourceBuilder.add("Value", val);
919 resourceBuilder.add("Value", decisionAttributes.get(key));
921 resourceBuilder.add("AttributeId", key);
922 resourceArray.add(resourceBuilder);
924 JsonObject model = Json
925 .createObjectBuilder()
927 Json.createObjectBuilder()
928 .add("AccessSubject",
929 Json.createObjectBuilder()
931 Json.createObjectBuilder()
937 Json.createObjectBuilder().add(
938 "Attribute", resourceArray))
940 Json.createObjectBuilder()
942 Json.createObjectBuilder()
946 "urn:oasis:names:tc:xacml:1.0:action:action-id"))))
950 policyDecision = decisionResult(generateRequest(model
951 .toString(), requestID));
952 } catch (Exception e) {
953 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
955 throw new PolicyDecisionException(e);
958 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Decision Attributes Given. ");
959 throw new PolicyDecisionException(XACMLErrorConstants.ERROR_DATA_ISSUE +"No DecisionAttributes Given.");
962 return policyDecision;
965 public Collection<PolicyConfig> configPolicyName(String policyName, UUID requestID, String userID, String passcode)
966 throws PolicyConfigException {
967 String resource= "getConfigByPolicyName";
968 if(!checkPermissions(userID, passcode, resource)){
969 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
970 throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
972 Collection<PolicyConfig> policyConfig = null;
973 if (policyName == null || policyName.isEmpty()) {
974 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "No Policy FileName specified!! : " + policyName);
975 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE+"No Policy FileName specified!!");
977 if(policyName!= null && !policyName.trim().equals("") && !policyName.endsWith("xml")){
978 policyName = policyName + ".[\\d].*";
980 JsonObject model = Json
981 .createObjectBuilder()
983 Json.createObjectBuilder()
984 .add("AccessSubject",
985 Json.createObjectBuilder().add(
987 Json.createObjectBuilder()
993 Json.createObjectBuilder()
995 Json.createObjectBuilder()
999 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1001 Json.createObjectBuilder()
1003 Json.createObjectBuilder()
1007 "urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))
1010 policyConfig = configResult(generateRequest(model.toString(), requestID));
1011 } catch (Exception e) {
1012 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1013 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1015 return policyConfig;
1018 public Collection<PolicyConfig> config(String eCOMPComponentName, UUID requestID, String userID, String passcode)
1019 throws PolicyConfigException {
1020 String resource= "getConfig";
1021 if(!checkPermissions(userID, passcode, resource)){
1022 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1023 throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1025 Collection<PolicyConfig> policyConfig = null;
1026 if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) {
1027 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName);
1028 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given.");
1030 JsonObject model = Json
1031 .createObjectBuilder()
1033 Json.createObjectBuilder()
1034 .add("AccessSubject",
1035 Json.createObjectBuilder()
1037 Json.createObjectBuilder()
1043 Json.createObjectBuilder()
1045 Json.createObjectBuilder()
1049 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1051 Json.createObjectBuilder()
1053 Json.createObjectBuilder()
1057 "urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))
1060 policyConfig = configResult(generateRequest(model.toString(), requestID));
1061 } catch (Exception e) {
1062 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1063 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1065 return policyConfig;
1068 public Collection<PolicyConfig> config(String eCOMPComponentName,
1069 String configName, UUID requestID, String userID, String passcode) throws PolicyConfigException {
1070 String resource= "getConfig";
1071 if(!checkPermissions(userID, passcode, resource)){
1072 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1073 throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1075 Collection<PolicyConfig> policyConfig = null;
1076 if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) {
1077 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName);
1078 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given.");
1080 if (configName == null || configName.isEmpty()) {
1081 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No configName given : " + configName);
1082 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"No configName given.");
1084 JsonObject model = Json
1085 .createObjectBuilder()
1087 Json.createObjectBuilder()
1088 .add("AccessSubject",
1089 Json.createObjectBuilder()
1091 Json.createArrayBuilder()
1093 .createObjectBuilder()
1099 .createObjectBuilder()
1105 Json.createObjectBuilder()
1107 Json.createObjectBuilder()
1111 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1113 Json.createObjectBuilder()
1115 Json.createObjectBuilder()
1119 "urn:oasis:names:tc:xacml:1.0:resource:resource-id"))))
1122 policyConfig = configResult(generateRequest(model.toString(), requestID));
1123 } catch (Exception e) {
1124 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1125 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1128 return policyConfig;
1131 public Collection<PolicyConfig> config(String eCOMPComponentName,
1132 String configName, Map<String, String> configAttributes, UUID requestID, String userID, String passcode)
1133 throws PolicyConfigException {
1134 String resource= "getConfig";
1135 if(!checkPermissions(userID, passcode, resource)){
1136 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1137 throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1139 Collection<PolicyConfig> policyConfig = null;
1140 if (eCOMPComponentName == null || eCOMPComponentName.isEmpty()) {
1141 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given : " + eCOMPComponentName);
1142 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName given.");
1144 if (configName == null || configName.isEmpty()) {
1145 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No configName given : " + configName);
1146 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"No configName given.");
1148 if (configAttributes != null && !configAttributes.isEmpty()) {
1149 if(!configAttributes.containsKey("RiskType")){
1150 configAttributes.put("RiskType", ".*");
1152 if(!configAttributes.containsKey("RiskLevel")){
1153 configAttributes.put("RiskLevel", ".*");
1155 if(!configAttributes.containsKey("guard")){
1156 configAttributes.put("guard", ".*");
1158 if(!configAttributes.containsKey("TTLDate")){
1159 configAttributes.put("TTLDate", ".*");
1162 // ConfigAttributes is Null. So add basic values.
1163 configAttributes = new HashMap<String,String>();
1164 configAttributes.put("RiskType", ".*");
1165 configAttributes.put("RiskLevel", ".*");
1166 configAttributes.put("guard", ".*");
1167 configAttributes.put("TTLDate", ".*");
1169 JsonArrayBuilder resourceArray = Json.createArrayBuilder();
1170 for (String key : configAttributes.keySet()) {
1171 if (key.isEmpty()) {
1172 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an empty Key");
1173 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"Cannot have an empty Key");
1175 JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
1176 /*if (configAttributes.get(key).matches("[0-9]+")) {
1177 int val = Integer.parseInt(configAttributes.get(key));
1178 resourceBuilder.add("Value", val);
1180 resourceBuilder.add("Value", configAttributes.get(key));
1181 resourceBuilder.add("AttributeId", key);
1182 resourceArray.add(resourceBuilder);
1184 JsonObject model = Json
1185 .createObjectBuilder()
1187 Json.createObjectBuilder()
1188 .add("AccessSubject",
1189 Json.createObjectBuilder()
1191 Json.createArrayBuilder()
1193 .createObjectBuilder()
1199 .createObjectBuilder()
1205 Json.createObjectBuilder()
1207 Json.createObjectBuilder()
1211 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1213 Json.createObjectBuilder()
1216 .add(Json.createObjectBuilder()
1220 "urn:oasis:names:tc:xacml:1.0:resource:resource-id")))))
1223 policyConfig = configResult(generateRequest(model.toString(), requestID));
1224 } catch (Exception e) {
1225 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1226 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1228 return policyConfig;
1231 public Collection<PolicyConfig> configRequest(ConfigRequestParameters configRequestParameters, String userID, String passcode) throws PolicyConfigException{
1232 String resource= "getConfig";
1233 if(!checkPermissions(userID, passcode, resource)){
1234 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1235 throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1237 Collection<PolicyConfig> policyConfig = null;
1239 if(configRequestParameters==null){
1240 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No config Request Parameters given ");
1241 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No config Request Parameters given.");
1243 if(configRequestParameters.getEcompName() == null && configRequestParameters.getPolicyName() == null){
1244 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot proceed without eCOMPComponentName or PolicyName");
1245 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No eCOMPComponentName or PolicyName given.");
1247 String policyName = configRequestParameters.getPolicyName();
1248 if(policyName!= null && !policyName.trim().equals("") && !policyName.endsWith("xml")){
1249 policyName = policyName + ".[\\d].*";
1251 JsonArrayBuilder subjectArray = Json.createArrayBuilder();
1252 JsonArrayBuilder resourceArray = Json.createArrayBuilder();
1253 if(configRequestParameters.getPolicyName()!=null){
1254 JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
1255 subjectBuilder.add("Value", policyName);
1256 subjectBuilder.add("AttributeId", "PolicyName");
1257 subjectArray.add(subjectBuilder);
1259 logger.info("PolicyName values are not given. ");
1261 if(configRequestParameters.getEcompName()!=null){
1262 JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
1263 subjectBuilder.add("Value", configRequestParameters.getEcompName());
1264 subjectBuilder.add("AttributeId", "ECOMPName");
1265 subjectArray.add(subjectBuilder);
1266 if(configRequestParameters.getConfigName()!=null){
1267 subjectBuilder = Json.createObjectBuilder();
1268 subjectBuilder.add("Value", configRequestParameters.getConfigName());
1269 subjectBuilder.add("AttributeId", "ConfigName");
1270 subjectArray.add(subjectBuilder);
1271 Map<String,String> configAttributes = configRequestParameters.getConfigAttributes();
1272 if (configAttributes != null && !configAttributes.isEmpty()) {
1273 if(!configAttributes.containsKey("RiskType")){
1274 configAttributes.put("RiskType", ".*");
1276 if(!configAttributes.containsKey("RiskLevel")){
1277 configAttributes.put("RiskLevel", ".*");
1279 if(!configAttributes.containsKey("guard")){
1280 configAttributes.put("guard", ".*");
1282 if(!configAttributes.containsKey("TTLDate")){
1283 configAttributes.put("TTLDate", ".*");
1286 // ConfigAttributes is Null. So add basic values.
1287 configAttributes = new HashMap<String,String>();
1288 configAttributes.put("RiskType", ".*");
1289 configAttributes.put("RiskLevel", ".*");
1290 configAttributes.put("guard", ".*");
1291 configAttributes.put("TTLDate", ".*");
1293 for (String key : configAttributes.keySet()) {
1294 if (key.isEmpty()) {
1295 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an empty Key");
1296 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"Cannot have an empty Key");
1298 JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
1299 /*if (configAttributes.get(key).matches("[0-9]+")) {
1300 int val = Integer.parseInt(configAttributes.get(key));
1301 resourceBuilder.add("Value", val);
1303 resourceBuilder.add("Value", configAttributes.get(key));
1304 resourceBuilder.add("AttributeId", key);
1305 resourceArray.add(resourceBuilder);
1308 logger.info("Config Name is not given. ");
1311 logger.info("Ecomp Name is not given. ");
1313 JsonObject model = Json
1314 .createObjectBuilder()
1316 Json.createObjectBuilder()
1317 .add("AccessSubject",
1318 Json.createObjectBuilder()
1319 .add("Attribute",subjectArray))
1321 Json.createObjectBuilder()
1323 Json.createObjectBuilder()
1327 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1329 Json.createObjectBuilder()
1333 .createObjectBuilder()
1337 "urn:oasis:names:tc:xacml:1.0:resource:resource-id")))))
1339 logger.debug("Generated JSON Request is: " + model.toString());
1340 if(configRequestParameters.getUnique()){
1341 logger.info("Requested for Unique Result only. ");
1345 policyConfig = configResult(generateRequest(model.toString(), configRequestParameters.getRequestID()));
1346 } catch (Exception e) {
1347 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1348 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1350 return policyConfig;
1353 public Collection<String> listConfigRequest(ConfigRequestParameters listRequestParameters, String userID, String passcode) throws PolicyConfigException{
1354 String resource= "listConfig";
1355 if(!checkPermissions(userID, passcode, resource)){
1356 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1357 throw new PolicyConfigException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1359 Collection<PolicyConfig> policyConfig = null;
1360 Collection<String> policyList = new ArrayList<String>();
1363 if(listRequestParameters==null){
1364 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Request Parameters given ");
1365 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Request Parameters given.");
1369 policyList.add("Policy Name: listConfigTest");
1373 String policyName = listRequestParameters.getPolicyName();
1374 if(policyName!= null && !policyName.trim().equals("") && !policyName.endsWith("xml")){
1375 policyName = policyName + ".[\\d].*";
1377 JsonArrayBuilder subjectArray = Json.createArrayBuilder();
1378 JsonArrayBuilder resourceArray = Json.createArrayBuilder();
1379 if(listRequestParameters.getPolicyName()!=null){
1380 JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
1381 subjectBuilder.add("Value", policyName);
1382 subjectBuilder.add("AttributeId", "PolicyName");
1383 subjectArray.add(subjectBuilder);
1385 logger.info("PolicyName values are not given. ");
1387 if(listRequestParameters.getEcompName()!=null){
1388 JsonObjectBuilder subjectBuilder = Json.createObjectBuilder();
1389 subjectBuilder.add("Value", listRequestParameters.getEcompName());
1390 subjectBuilder.add("AttributeId", "ECOMPName");
1391 subjectArray.add(subjectBuilder);
1392 if(listRequestParameters.getConfigName()!=null){
1393 subjectBuilder = Json.createObjectBuilder();
1394 subjectBuilder.add("Value", listRequestParameters.getConfigName());
1395 subjectBuilder.add("AttributeId", "ConfigName");
1396 subjectArray.add(subjectBuilder);
1397 Map<String,String> configAttributes = listRequestParameters.getConfigAttributes();
1398 if (configAttributes != null && !configAttributes.isEmpty()) {
1399 if(!configAttributes.containsKey("RiskType")){
1400 configAttributes.put("RiskType", ".*");
1402 if(!configAttributes.containsKey("RiskLevel")){
1403 configAttributes.put("RiskLevel", ".*");
1405 if(!configAttributes.containsKey("guard")){
1406 configAttributes.put("guard", ".*");
1408 if(!configAttributes.containsKey("TTLDate")){
1409 configAttributes.put("TTLDate", ".*");
1412 // ConfigAttributes is Null. So add basic values.
1413 configAttributes = new HashMap<String,String>();
1414 configAttributes.put("RiskType", ".*");
1415 configAttributes.put("RiskLevel", ".*");
1416 configAttributes.put("guard", ".*");
1417 configAttributes.put("TTLDate", ".*");
1419 for (String key : configAttributes.keySet()) {
1420 if (key.isEmpty()) {
1421 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an empty Key");
1422 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +"Cannot have an empty Key");
1424 JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
1425 /*if (configAttributes.get(key).matches("[0-9]+")) {
1426 int val = Integer.parseInt(configAttributes.get(key));
1427 resourceBuilder.add("Value", val);
1429 resourceBuilder.add("Value", configAttributes.get(key));
1430 resourceBuilder.add("AttributeId", key);
1431 resourceArray.add(resourceBuilder);
1434 logger.info("Config Name is not given. ");
1437 logger.info("Ecomp Name is not given. ");
1439 JsonObject model = Json
1440 .createObjectBuilder()
1442 Json.createObjectBuilder()
1443 .add("AccessSubject",
1444 Json.createObjectBuilder()
1445 .add("Attribute",subjectArray))
1447 Json.createObjectBuilder()
1449 Json.createObjectBuilder()
1453 "urn:oasis:names:tc:xacml:1.0:action:action-id")))
1455 Json.createObjectBuilder()
1459 .createObjectBuilder()
1463 "urn:oasis:names:tc:xacml:1.0:resource:resource-id")))))
1465 logger.debug("Generated JSON Request is: " + model.toString());
1466 if(listRequestParameters.getUnique()){
1467 logger.info("Requested for Unique Result only. ");
1471 policyConfig = configResult(generateRequest(model.toString(), listRequestParameters.getRequestID()));
1472 } catch (Exception e) {
1473 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1474 throw new PolicyConfigException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1476 for(PolicyConfig policy : policyConfig){
1477 if(policy.getPolicyConfigMessage()!=null && policy.getPolicyConfigMessage().contains("PE300")){
1478 policyList.add(policy.getPolicyConfigMessage());
1480 policyList.add("Policy Name: " + policy.getPolicyName());
1488 public Collection<PolicyResponse> event(Map<String, String> eventAttributes, UUID requestID, String userID, String passcode)
1489 throws PolicyEventException {
1490 String resource= "sendEvent";
1491 if(!checkPermissions(userID, passcode, resource)){
1492 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1493 throw new PolicyEventException(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
1495 Collection<PolicyResponse> policyResponse = null;
1496 if (eventAttributes != null && !eventAttributes.isEmpty()) {
1497 JsonArrayBuilder resourceArray = Json.createArrayBuilder();
1498 for (String key : eventAttributes.keySet()) {
1499 if (key.isEmpty()) {
1500 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot have an Empty Key");
1501 throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +"Cannot have an empty Key");
1503 JsonObjectBuilder resourceBuilder = Json.createObjectBuilder();
1504 if (eventAttributes.get(key).matches("[0-9]+")) {
1505 int val = Integer.parseInt(eventAttributes.get(key));
1506 resourceBuilder.add("Value", val);
1508 resourceBuilder.add("Value", eventAttributes.get(key));
1510 resourceBuilder.add("AttributeId", key);
1511 resourceArray.add(resourceBuilder);
1513 JsonObject model = Json
1514 .createObjectBuilder()
1516 Json.createObjectBuilder().add(
1518 Json.createObjectBuilder().add("Attribute",
1519 resourceArray))).build();
1520 // Removed Part can be Useful in Future.
1522 * .add("AccessSubject",Json.createObjectBuilder() .add("Attribute",
1523 * subjectArray)) .add("Action", Json.createObjectBuilder()
1524 * .add("Attribute", actionArray))
1526 // System.out.println(model.toString());
1528 // StdPolicyResponse stdPolicyResponse =
1529 // generateRequest(model.toString());
1530 // stdPolicyResponse.setRequestAttributes(eventAttributes);
1531 policyResponse = eventResult(generateRequest(model.toString(), requestID),
1533 } catch (Exception e) {
1534 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1535 throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +e);
1538 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No event Attributes Given. ");
1539 throw new PolicyEventException(XACMLErrorConstants.ERROR_DATA_ISSUE +"No EventAttributes Given.");
1541 return policyResponse;
1544 private Collection<StdStatus> generateRequest(String Json, UUID requestID) throws Exception {
1545 Collection<StdStatus> results = null;
1547 Response response = null;
1548 // Create Request. We need XACML API here.
1550 Request request = JSONRequest.load(Json);
1551 String jRequest = JSONRequest.toString(request);
1554 logger.debug("--- Generating Request: ---\n" + jRequest );
1555 response = callPDP(new ByteArrayInputStream(jRequest.getBytes()), requestID);
1557 } catch (Exception e) {
1558 logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e);
1559 StdStatus stdStatus = new StdStatus();
1560 results = new HashSet<StdStatus>();
1561 stdStatus.setStatus("Unable to Call PDP. Error with the URL",
1562 PolicyResponseStatus.NO_ACTION_REQUIRED,
1563 PolicyConfigStatus.CONFIG_NOT_FOUND);
1564 results.add(stdStatus);
1565 throw new Exception(e);
1569 this.UEBThread = registerUEBThread.isAlive();
1571 if (response != null) {
1572 results = checkResponse(response);
1573 // TODO Starting Auto Client Here.
1574 if (notificationType.get(0).equals("ueb") && !this.UEBThread){
1575 this.UEBClientThread = new AutoClientUEB(pdps.get(0), uebURLList);
1576 this.registerUEBThread = new Thread(this.UEBClientThread);
1577 this.registerUEBThread.start();
1578 this.UEBThread = true;
1581 if(AutoClientEnd.getURL()==null){
1582 AutoClientEnd.start(pdps.get(0));
1583 }else if(AutoClientEnd.getURL()!=pdps.get(0)){
1584 AutoClientEnd.stop();
1585 AutoClientEnd.start(pdps.get(0));
1589 logger.debug("No Response Received from PDP");
1590 StdStatus stdStatus = new StdStatus();
1591 results = new HashSet<StdStatus>();
1592 stdStatus.setStatus("No Response Received",
1593 PolicyResponseStatus.NO_ACTION_REQUIRED,
1594 PolicyConfigStatus.CONFIG_NOT_FOUND);
1595 results.add(stdStatus);
1601 private Response callPDP(ByteArrayInputStream input, UUID requestID) throws Exception {
1602 Response response = null;
1603 HttpURLConnection connection = null;
1605 // Checking for the available PDPs is done during the first Request and
1606 // the List is going to have the connected PDP as first element.
1607 // This makes it Real-Time to change the list depending on their
1609 if (pdps == null || pdps.isEmpty()) {
1610 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDPs List is Empty.");
1611 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PDPs List is empty.");
1614 boolean connected = false;
1615 while (pdpsCount < pdps.size()) {
1618 String urlValue = pdps.get(0);
1619 URL url = new URL(urlValue);
1620 logger.debug("--- Sending Request to PDP : "+ url.toString() + " ---");
1621 connection = (HttpURLConnection) url.openConnection();
1622 // Setting Content-Type
1623 connection.setRequestProperty("Content-Type","application/json");
1624 // Adding Authorization
1625 connection.setRequestProperty("Authorization", "Basic " + encoding.get(0));
1626 // Adding Environment.
1627 connection.setRequestProperty("Environment", environment);
1629 if (requestID == null) {
1630 requestID = UUID.randomUUID();
1631 logger.info("No request ID provided, sending generated ID: " + requestID.toString());
1633 logger.info("Using provided request ID: " + requestID.toString());
1635 connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
1636 // Setting up connection method and headers.
1637 connection.setRequestMethod("POST");
1638 connection.setUseCaches(false);
1639 connection.setInstanceFollowRedirects(false);
1640 connection.setDoOutput(true);
1641 connection.setDoInput(true);
1642 OutputStream os = connection.getOutputStream();
1643 IOUtils.copy(input, os);
1646 connection.connect();
1647 responseCode = connection.getResponseCode();
1648 // If Connected to a PDP Then break from the loop and
1649 // continue with the Request.
1650 if (connection.getResponseCode() == 200 || junit) {
1654 logger.debug(XACMLErrorConstants.ERROR_PERMISSIONS+ "PDP Response Code : " + connection.getResponseCode());
1655 Collections.rotate(pdps, -1);
1656 Collections.rotate(encoding, -1);
1658 } catch (Exception e) {
1659 // This means that the PDP is not working and needs to
1660 // Re-Order our List and Connect to the next one.
1661 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP connection Error : " + e);
1662 Collections.rotate(pdps, -1);
1663 Collections.rotate(encoding, -1);
1668 // Read the Response
1669 // System.out.println("connected to PDP : " + pdps.get(0));
1670 logger.debug("connected to PDP : " + pdps.get(0));
1671 logger.debug("--- Response: ---");
1672 Map<String,List<String>> headers = connection.getHeaderFields();
1673 for(String key : headers.keySet()){
1674 logger.debug("Header : " + key + " Value: " + headers.get(key));
1677 if (connection.getResponseCode() == 200 || junit) {
1678 // Read the Response
1679 ContentType contentType = null;
1681 contentType = ContentType.parse(connection
1683 if (contentType.getMimeType().equalsIgnoreCase(
1684 ContentType.APPLICATION_JSON.getMimeType())) {
1686 response = JSONResponse.load(getJsonResponseString());
1688 response = JSONResponse.load(connection.getInputStream());
1690 logger.debug(response + "\n---");
1692 logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unknown Content-Type: "
1694 throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unknown Content-Type: "
1697 } catch (Exception e) {
1698 String message = XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Parsing Content-Type: "
1699 + connection.getContentType() + ", error="
1701 logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e);
1702 throw new Exception(message, e);
1705 throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS+ "ERROR response code of the URL " + pdps.get(0) + " is "
1706 + connection.getResponseCode());
1708 } catch (IOException e) {
1709 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
1710 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error in Connecting to the PDP ", e);
1715 response = JSONResponse.load(getJsonResponseString());
1718 throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS+ "Unable to get valid Response from PDP(s) " + pdps);
1723 private Collection<StdStatus> checkResponse(Response response)
1726 String pdpConfigURL = null;
1728 Collection<StdStatus> combinedResult = new HashSet<StdStatus>();
1729 int priority = defaultPriority;
1730 Map<Integer, StdStatus> uniqueResult = new HashMap<Integer, StdStatus>();
1731 for (Result result : response.getResults()) {
1732 if (!result.getDecision().equals(Decision.PERMIT)) {
1733 logger.debug("Decision not a Permit. " + result.getDecision().toString());
1734 StdStatus stdStatus = new StdStatus();
1736 stdStatus.setDecision(PolicyDecision.DENY);
1737 for(Advice advice: result.getAssociatedAdvice()){
1738 for(AttributeAssignment attribute: advice.getAttributeAssignments()){
1739 stdStatus.setDetails(attribute.getAttributeValue().getValue().toString());
1743 combinedResult.add(stdStatus);
1744 return combinedResult;
1746 stdStatus.setStatus(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Params passed: Decision not a Permit.",PolicyResponseStatus.NO_ACTION_REQUIRED,PolicyConfigStatus.CONFIG_NOT_FOUND);
1747 combinedResult.add(stdStatus);
1748 return combinedResult;
1751 // check for Decision for decision based calls.
1752 StdStatus stdStatus = new StdStatus();
1753 stdStatus.setDecision(PolicyDecision.PERMIT);
1754 stdStatus.setDetails("Decision Permit. OK!");
1755 combinedResult.add(stdStatus);
1756 return combinedResult;
1758 if (!result.getAssociatedAdvice().isEmpty()) {
1759 // @ TODO Add advice actions
1760 // Configurations should be in advice. + Also PDP took
1761 // actions could be here.
1762 for (Advice advice : result.getAssociatedAdvice()) {
1763 int config = 0, uri = 0;
1764 String configURL = null;
1765 String policyName = null;
1766 String policyVersion = null;
1767 Map<String, String> matchingConditions = new HashMap<String, String>();
1768 match = new Matches();
1769 Map<String, String> configAttributes = new HashMap<String, String>();
1770 Map<String, String> responseAttributes = new HashMap<String,String>();
1771 Map<String, String> actionTaken = new HashMap<String, String>();
1772 StdStatus stdStatus = new StdStatus();
1773 Map<String, String> adviseAttributes = new HashMap<String, String>();
1774 for (AttributeAssignment attribute : advice.getAttributeAssignments()) {
1775 adviseAttributes.put(attribute.getAttributeId().stringValue(), attribute.getAttributeValue().getValue().toString());
1776 if (attribute.getAttributeValue().getValue().toString().equalsIgnoreCase("CONFIGURATION")) {
1778 } else if (attribute.getDataTypeId().stringValue().endsWith("anyURI")) {
1781 configURL = attribute.getAttributeValue().getValue().toString();
1782 String currentUsedPDP = pdps.get(0);
1783 int pos = (pdps.get(0)).lastIndexOf("/");
1784 String configURLPath = currentUsedPDP.substring(0, pos);
1785 int pos1 = configURLPath.lastIndexOf("/");
1786 String pdpConfigURLPath = configURLPath.substring(0, pos1 + 1);
1787 pdpConfigURL = configURL.replace("$URL", pdpConfigURLPath);
1789 if (!(attribute.getIssuer().equalsIgnoreCase("PDP"))) {
1790 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error having multiple URI in the Policy");
1793 } else if (attribute.getAttributeId().stringValue()
1794 .equalsIgnoreCase("PolicyName")) {
1795 policyName = attribute.getAttributeValue()
1796 .getValue().toString();
1797 } else if (attribute.getAttributeId().stringValue()
1798 .equalsIgnoreCase("VersionNumber")) {
1799 policyVersion = attribute.getAttributeValue()
1800 .getValue().toString();
1801 } else if (attribute.getAttributeId().stringValue().equalsIgnoreCase("Priority")){
1803 priority = Integer.parseInt(attribute.getAttributeValue().getValue().toString());
1804 } catch(Exception e){
1805 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ "Unable to Parse Integer for Priority. Setting to default value");
1806 priority = defaultPriority;
1808 } else if (attribute.getAttributeId().stringValue()
1809 .startsWith("matching")) {
1810 matchingConditions.put(attribute
1811 .getAttributeId().stringValue()
1812 .replaceFirst("(matching).", ""),
1813 attribute.getAttributeValue()
1814 .getValue().toString());
1815 if (attribute.getAttributeId().stringValue()
1816 .replaceFirst("(matching).", "")
1817 .equals("ECOMPName")) {
1818 match.setEcompName(attribute
1819 .getAttributeValue().getValue()
1821 } else if (attribute.getAttributeId()
1823 .replaceFirst("(matching).", "")
1824 .equals("ConfigName")) {
1825 match.setConfigName(attribute
1826 .getAttributeValue().getValue()
1829 configAttributes.put(attribute
1830 .getAttributeId().stringValue()
1831 .replaceFirst("(matching).", ""),
1832 attribute.getAttributeValue()
1833 .getValue().toString());
1835 } else if (attribute.getAttributeId().stringValue().startsWith("key:")) {
1836 responseAttributes.put(attribute
1837 .getAttributeId().stringValue()
1838 .replaceFirst("(key).", ""),
1839 attribute.getAttributeValue()
1840 .getValue().toString());
1843 if (!configAttributes.isEmpty()) {
1844 match.setConfigAttributes(configAttributes);
1846 if ((config == 1) && (uri == 1)) {
1847 // If there is a configuration.
1849 logger.debug("Configuration Call to : "
1851 stdStatus = ConfigCall(pdpConfigURL);
1852 } catch (Exception e) {
1853 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+ e);
1856 "Error in Calling the Configuration URL "
1858 PolicyResponseStatus.NO_ACTION_REQUIRED,
1859 PolicyConfigStatus.CONFIG_NOT_FOUND);
1861 stdStatus.setPolicyName(policyName);
1862 stdStatus.setPolicyVersion(policyVersion);
1863 stdStatus.setMatchingConditions(matchingConditions);
1864 stdStatus.setResposneAttributes(responseAttributes);
1866 combinedResult.add(stdStatus);
1868 if(!uniqueResult.isEmpty()){
1869 if(uniqueResult.containsKey(priority)){
1870 // Not any more unique, check the matching conditions size
1871 int oldSize = uniqueResult.get(priority).getMatchingConditions().size();
1872 int newSize = matchingConditions.size();
1873 if(oldSize < newSize){
1874 uniqueResult.put(priority, stdStatus);
1875 }else if(oldSize == newSize){
1876 stdStatus = new StdStatus();
1877 stdStatus.setStatus("Two/more Policies have Same Priority and matching conditions, Please correct your policies.", PolicyResponseStatus.NO_ACTION_REQUIRED,
1878 PolicyConfigStatus.CONFIG_NOT_FOUND);
1879 combinedResult.add(stdStatus);
1881 return combinedResult;
1884 uniqueResult.put(priority, stdStatus);
1887 uniqueResult.put(priority, stdStatus);
1891 // Else it is Action Taken.
1892 logger.info("Action Taken by PDP. ");
1893 actionTaken.putAll(adviseAttributes);
1894 stdStatus.setActionTaken(actionTaken);
1895 stdStatus.setPolicyResponseStatus(
1896 "Action Taken by the PDP",
1897 PolicyResponseStatus.ACTION_TAKEN);
1898 combinedResult.add(stdStatus);
1902 if (!result.getObligations().isEmpty()) {
1903 // @ TODO add Obligation actions
1904 // Action advised should be in obligations.
1905 for (Obligation obligation : result.getObligations()) {
1906 Map<String, String> actionAdvised = new HashMap<String, String>();
1907 StdStatus stdStatus = new StdStatus();
1908 for (AttributeAssignment attribute : obligation
1909 .getAttributeAssignments()) {
1910 actionAdvised.put(attribute.getAttributeId()
1911 .stringValue(), attribute
1912 .getAttributeValue().getValue().toString());
1914 stdStatus.setActionAdvised(actionAdvised);
1915 stdStatus.setPolicyResponseStatus(
1916 "Action has been Advised ",
1917 PolicyResponseStatus.ACTION_ADVISED);
1918 combinedResult.add(stdStatus);
1924 // Select Unique policy.
1925 int minNum = defaultPriority;
1926 for(int num: uniqueResult.keySet()){
1931 combinedResult.add(uniqueResult.get(minNum));
1936 return combinedResult;
1939 private StdStatus ConfigCall(String stringURL) throws Exception {
1940 StdStatus stdStatus = new StdStatus();
1942 URL configURL = new URL(stringURL);
1943 URLConnection connection = null;
1945 connection = configURL.openConnection();
1946 if (stringURL.endsWith("json")) {
1947 stdStatus.setPolicyType(PolicyType.JSON);
1948 JsonReader jsonReader = Json.createReader(connection
1950 stdStatus.setJsonObject(jsonReader.readObject());
1952 logger.info("config Retrieved ");
1953 stdStatus.setStatus("Config Retrieved from: " + configURL,
1954 PolicyResponseStatus.NO_ACTION_REQUIRED,
1955 PolicyConfigStatus.CONFIG_RETRIEVED);
1957 MatchStore.storeMatch(match);
1958 } catch (Exception e) {
1959 logger.info("StoreMatch failed for Ecomp:"
1960 + match.getEcompName() + " Config: "
1961 + match.getConfigName());
1964 } else if (stringURL.endsWith("xml")) {
1965 stdStatus.setPolicyType(PolicyType.XML);
1966 DocumentBuilderFactory dbf = DocumentBuilderFactory
1968 DocumentBuilder db = null;
1970 db = dbf.newDocumentBuilder();
1971 Document config = db.parse(connection.getInputStream());
1972 stdStatus.setDocument(config);
1973 } catch (ParserConfigurationException e) {
1974 logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + e);
1975 throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Unable to create Document Object",
1977 } catch (SAXException e) {
1978 logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ e);
1979 throw new Exception(XACMLErrorConstants.ERROR_SCHEMA_INVALID+ "Unable to parse the XML config", e);
1981 logger.info("config Retrieved ");
1982 stdStatus.setStatus("Config Retrieved from: " + configURL,
1983 PolicyResponseStatus.NO_ACTION_REQUIRED,
1984 PolicyConfigStatus.CONFIG_RETRIEVED);
1986 MatchStore.storeMatch(match);
1987 } catch (Exception e) {
1988 logger.info("StoreMatch failed for Ecomp:"
1989 + match.getEcompName() + " Config: "
1990 + match.getConfigName());
1993 } else if (stringURL.endsWith("properties")) {
1994 stdStatus.setPolicyType(PolicyType.PROPERTIES);
1995 Properties configProp = new Properties();
1996 configProp.load(connection.getInputStream());
1997 stdStatus.setProperties(configProp);
1998 logger.info("config Retrieved ");
1999 stdStatus.setStatus("Config Retrieved from: " + configURL,
2000 PolicyResponseStatus.NO_ACTION_REQUIRED,
2001 PolicyConfigStatus.CONFIG_RETRIEVED);
2003 MatchStore.storeMatch(match);
2004 } catch (Exception e) {
2005 logger.info("StoreMatch failed for Ecomp:"
2006 + match.getEcompName() + " Config: "
2007 + match.getConfigName());
2010 } else if (stringURL.endsWith("txt")) {
2011 stdStatus.setPolicyType(PolicyType.OTHER);
2012 InputStream in = connection.getInputStream();
2013 String other = IOUtils.toString(in);
2014 IOUtils.closeQuietly(in);
2015 stdStatus.setOther(other);
2016 logger.info("config Retrieved ");
2017 stdStatus.setStatus("Config Retrieved from: " + configURL,
2018 PolicyResponseStatus.NO_ACTION_REQUIRED,
2019 PolicyConfigStatus.CONFIG_RETRIEVED);
2021 MatchStore.storeMatch(match);
2022 } catch (Exception e) {
2023 logger.info("StoreMatch failed for Ecomp:"
2024 + match.getEcompName() + " Config: "
2025 + match.getConfigName());
2029 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Config Not Found");
2031 .setPolicyConfigStatus(PolicyConfigStatus.CONFIG_NOT_FOUND);
2033 .setConfigStatus("Illegal form of Configuration Type Found.");
2036 } catch (IOException e) {
2037 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
2038 throw new Exception(XACMLErrorConstants.ERROR_PROCESS_FLOW +
2039 "Cannot open a connection to the configURL", e);
2041 } catch (MalformedURLException e) {
2042 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
2043 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in ConfigURL", e);
2047 private void setProperty(String propertyFilePath)
2048 throws PolicyEngineException {
2049 this.propertyFilePath = propertyFilePath;
2050 if (this.propertyFilePath == null) {
2051 // This is only for testing purpose. Or We will add a default PDP
2053 // url_default = "http://localhost:8080/pdp/";
2054 // The General Error Message is Below.
2055 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error NO PropertyFile Path provided");
2057 // Adding logic for remote Properties file.
2058 Properties prop = new Properties();
2059 if (propertyFilePath.startsWith("http")) {
2062 configURL = new URL(propertyFilePath);
2063 URLConnection connection = null;
2064 connection = configURL.openConnection();
2065 prop.load(connection.getInputStream());
2066 } catch (IOException e) {
2067 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
2068 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Maformed property URL "+ e.getMessage());
2071 Path file = Paths.get(propertyFilePath);
2072 if (Files.notExists(file)) {
2073 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "File doesn't exist in the specified Path " + file.toString());
2075 if (file.toString().endsWith(".properties")) {
2077 prop = new Properties();
2079 in = new FileInputStream(file.toFile());
2081 } catch (IOException e) {
2082 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
2083 throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Load the Properties file", e);
2086 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + propertyFilePath);
2087 throw new PolicyEngineException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file");
2091 String check_type = prop.getProperty("NOTIFICATION_TYPE");
2092 String serverList = prop.getProperty("NOTIFICATION_UEB_SERVERS");
2093 if(check_type==null) {
2094 notificationType.add("websocket");
2095 logger.info("Properties file doesn't have the NOTIFICATION_TYPE parameter system will use defualt websockets");
2097 if(check_type.contains(",")) {
2098 type_default = new ArrayList<String>(Arrays.asList(prop.getProperty("NOTIFICATION_TYPE").split(",")));
2099 notificationType = type_default;
2101 notificationType = new ArrayList<String>();
2102 notificationType.add(check_type);
2105 if(serverList==null) {
2106 notificationType.clear();
2107 notificationType.add("websocket");
2108 logger.info("Properties file doesn't have the NOTIFICATION_UEB_SERVERS parameter system will use defualt websockets");
2110 if(serverList.contains(",")) {
2111 uebURLList = new ArrayList<String>(Arrays.asList(prop.getProperty("NOTIFICATION_UEB_SERVERS").split(",")));
2113 uebURLList = new ArrayList<String>();
2114 uebURLList.add(serverList);
2117 // Client ID Authorization Settings.
2118 String clientID = prop.getProperty("CLIENT_ID");
2119 String clientKey = prop.getProperty("CLIENT_KEY");
2120 userName = clientID;
2122 pyPDPClientFile = prop.getProperty("CLIENT_FILE");
2123 environment = prop.getProperty("ENVIRONMENT", "DEVL");
2125 aafClient = AAFPolicyClient.getInstance(prop);
2126 } catch (AAFPolicyException e) {
2127 logger.error(XACMLErrorConstants.ERROR_UNKNOWN + e.getMessage());
2128 throw new PolicyEngineException(XACMLErrorConstants.ERROR_UNKNOWN + e);
2130 // Initializing the values.
2131 pdps = new ArrayList<String>();
2132 paps = new ArrayList<String>();
2133 encoding = new ArrayList<String>();
2134 encodingPAP = new ArrayList<String>();
2135 // Check the Keys for PDP_URLs
2136 Collection<Object> unsorted = prop.keySet();
2137 @SuppressWarnings({ "rawtypes", "unchecked" })
2138 List<String> sorted = new ArrayList(unsorted);
2139 Collections.sort(sorted);
2140 for (String propKey : sorted) {
2141 if (propKey.startsWith("PDP_URL")) {
2142 String check_val = prop.getProperty(propKey);
2143 if (check_val == null) {
2144 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Properties file doesn't have the PDP_URL parameter");
2146 if (check_val.contains(";")) {
2147 pdp_default = new ArrayList<String>(Arrays.asList(check_val.split("\\s*;\\s*")));
2149 while (pdpCount < pdp_default.size()) {
2150 String pdpVal = pdp_default.get(pdpCount);
2151 readPDPParam(pdpVal);
2155 readPDPParam(check_val);
2157 } else if (propKey.startsWith("PAP_URL")) {
2158 String check_val = prop.getProperty(propKey);
2159 if (check_val == null) {
2160 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Properties file doesn't have the PAP_URL parameter");
2162 if (check_val.contains(";")) {
2163 pap_default = new ArrayList<String>(Arrays.asList(check_val.split("\\s*;\\s*")));
2165 while (papCount < pap_default.size()) {
2166 String papVal = pap_default.get(papCount);
2167 readPAPParam(papVal);
2171 readPAPParam(check_val);
2175 if (pdps == null || pdps.isEmpty()) {
2176 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
2177 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PDP_URLs");
2180 if (paps == null || paps.isEmpty()) {
2181 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed without PAP_URLs");
2182 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot Proceed with out PAP_URLs");
2185 // Get JUNIT property from properties file when running tests
2186 String junit = prop.getProperty("JUNIT");
2187 if(junit == null || junit.isEmpty()){
2188 logger.info("No JUNIT property provided, this will not be executed as a test.");
2190 if(junit.equals("test")){
2200 * Read the PDP_URL parameter
2202 private void readPDPParam(String pdpVal) throws PolicyEngineException{
2203 if(pdpVal.contains(",")){
2204 List<String> pdpValues = new ArrayList<String>(Arrays.asList(pdpVal.split("\\s*,\\s*")));
2205 if(pdpValues.size()==3){
2207 pdps.add(pdpValues.get(0));
2208 // 1:2 will be UserID:Password
2209 String userID = pdpValues.get(1);
2210 String pass = pdpValues.get(2);
2211 Base64.Encoder encoder = Base64.getEncoder();
2212 encoding.add(encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
2214 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + pdpValues);
2215 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + pdpValues);
2218 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values: " + pdpVal);
2219 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "PDP value is improper/missing required values.");
2224 * Read the PAP_URL parameter
2226 private void readPAPParam(String papVal) throws PolicyEngineException{
2227 if(papVal.contains(",")){
2228 List<String> papValues = new ArrayList<String>(Arrays.asList(papVal.split("\\s*,\\s*")));
2229 if(papValues.size()==3){
2231 paps.add(papValues.get(0));
2232 // 1:2 will be UserID:Password
2233 String userID = papValues.get(1);
2234 String pass = papValues.get(2);
2235 Base64.Encoder encoder = Base64.getEncoder();
2236 encodingPAP.add(encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8)));
2238 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + papValues);
2239 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request. " + papValues);
2242 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Credentials to send Request: " + papVal);
2243 throw new PolicyEngineException(XACMLErrorConstants.ERROR_DATA_ISSUE + "No enough Credentials to send Request.");
2247 * Allowing changes to the scheme and Handler.
2249 public void notification(NotificationScheme scheme, NotificationHandler handler) {
2250 this.scheme = scheme;
2251 this.handler = handler;
2252 logger.debug("Scheme is : " + scheme.toString());
2253 logger.debug("Handler is : " + handler.getClass().getName());
2254 if (!notificationType.get(0).equals("ueb")){
2255 AutoClientEnd.setAuto(scheme, handler);
2257 if (this.UEBThread){
2258 UEBClientThread.setAuto(scheme, handler);
2259 this.UEBThread = registerUEBThread.isAlive();
2263 //TODO This could also be a Start point for Auto Notifications..
2265 if (notificationType.get(0).equals("ueb") && !this.UEBThread){
2266 this.UEBClientThread = new AutoClientUEB(pdps.get(0), uebURLList);
2267 this.UEBClientThread.setAuto(scheme, handler);
2268 this.registerUEBThread = new Thread(this.UEBClientThread);
2269 this.registerUEBThread.start();
2270 this.UEBThread = true;
2272 if (!notificationType.get(0).equals("ueb")){
2273 if(pdps.get(0)!=null){
2274 if(AutoClientEnd.getURL()==null){
2275 AutoClientEnd.start(pdps.get(0));
2277 AutoClientEnd.stop();
2278 AutoClientEnd.start(pdps.get(0));
2286 * Gets the Notification if one exists. Used only for Manual Polling
2289 public PDPNotification getNotification(){
2290 //TODO manual Polling
2291 //Check if there is proper scheme..
2292 PDPNotification notification = null;
2293 if(this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS) || this.scheme.equals(NotificationScheme.MANUAL_NOTIFICATIONS)) {
2294 if (notificationType.get(0).equals("ueb")){
2295 ManualClientEndUEB.start(pdps.get(0), uebURLList, uniqueID);
2296 notification = ManualClientEndUEB.result(scheme);
2298 ManualClientEnd.start(pdps.get(0));
2299 logger.debug("manual notification requested.. : " + scheme.toString());
2300 notification = ManualClientEnd.result(scheme);
2303 if (notification == null){
2304 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Notification yet..");
2307 return notification;
2316 * Setting the Scheme.
2318 public void setScheme(NotificationScheme scheme) {
2319 this.scheme = scheme;
2320 if (notificationType.get(0).equals("ueb")){
2321 AutoClientUEB.setScheme(this.scheme);
2322 if (this.scheme.equals(NotificationScheme.MANUAL_ALL_NOTIFICATIONS)){
2323 ManualClientEndUEB.createTopic(pdps.get(0), uniqueID, uebURLList);
2326 AutoClientEnd.setScheme(this.scheme);
2331 * Returns the Scheme
2333 public NotificationScheme getScheme() {
2338 * Returns the NotificationHandler
2340 public NotificationHandler getNotificationHandler() {
2341 return this.handler;
2344 private Collection<PolicyConfig> configResult(
2345 Collection<StdStatus> generateRequest) {
2346 Collection<PolicyConfig> result = new HashSet<PolicyConfig>();
2347 if (generateRequest == null) {
2350 if (!generateRequest.isEmpty()) {
2351 for (StdStatus stdStatus : generateRequest) {
2352 PolicyConfig policyConfig = new StdPolicyConfig();
2353 policyConfig = stdStatus;
2354 result.add(policyConfig);
2360 private Collection<PolicyResponse> eventResult(
2361 Collection<StdStatus> generateRequest,
2362 Map<String, String> eventAttributes) {
2363 Collection<PolicyResponse> result = new HashSet<PolicyResponse>();
2364 if (generateRequest == null) {
2367 if (!generateRequest.isEmpty()) {
2368 for (StdStatus stdStatus : generateRequest) {
2369 StdPolicyResponse policyResponse = new StdPolicyResponse();
2370 policyResponse = stdStatus;
2371 policyResponse.setRequestAttributes(eventAttributes);
2372 result.add(policyResponse);
2378 private DecisionResponse decisionResult(Collection<StdStatus> generateRequest) {
2379 StdDecisionResponse policyDecision = new StdDecisionResponse();
2380 if (generateRequest == null) {
2381 return policyDecision;
2383 if (!generateRequest.isEmpty()) {
2384 for (StdStatus stdStatus : generateRequest) {
2385 policyDecision.setDecision(stdStatus.getDecision());
2386 policyDecision.setDetails(stdStatus.getDetails());
2389 return policyDecision;
2393 * Stop the Notification Service if its running.
2395 public void stopNotification() {
2396 if (this.scheme != null && this.handler != null) {
2397 if (this.scheme.equals(NotificationScheme.AUTO_ALL_NOTIFICATIONS)
2399 .equals(NotificationScheme.AUTO_NOTIFICATIONS)) {
2400 logger.info("Clear Notification called.. ");
2401 if (notificationType.get(0).equals("ueb")){
2402 this.UEBClientThread.terminate();
2403 this.UEBThread = false;
2405 AutoClientEnd.stop();
2412 * Create Config Policy API Implementation
2414 public String createConfigPolicy(String policyName, String policyDescription, String ecompName, String configName,
2415 Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID,
2416 String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2417 return createConfigPolicy(policyName,policyDescription, ecompName, configName,
2418 configAttributes, configType, body, policyScope, requestID, userName , pass, riskLevel, riskType, guard, ttlDate);
2421 public String createConfigPolicy(String policyName, String policyDescription, String ecompName, String configName,
2422 Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID, String userID, String passcode,
2423 String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2425 String response = null;
2426 String configBody = null;
2427 String resource= "createPolicy";
2428 if(!checkPermissions(userID, passcode, resource)){
2429 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
2430 response = XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource;
2434 //check body for JSON form and remove single quotes if present
2435 if (configType.equalsIgnoreCase("JSON")) {
2436 if (body.contains("'")) {
2437 configBody = body.replace("'", "\"");
2445 boolean levelCheck = isNumeric(riskLevel);
2447 if (policyName==null||policyName.equalsIgnoreCase("")){
2448 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2449 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2450 } else if (ecompName==null||ecompName.equalsIgnoreCase("")){
2451 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.");
2452 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.";
2453 } else if (configName==null||configName.equalsIgnoreCase("")){
2454 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.");
2455 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.";
2456 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2457 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2458 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2459 } else if (!levelCheck){
2460 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2461 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2464 StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Base", policyName, policyDescription, ecompName, configName, configAttributes, configType,
2465 configBody, false, policyScope,0, riskLevel, riskType, guard, ttlDate);
2467 //send JSON object to PAP
2468 response = (String) callPAP(newPAPPolicy, new String[] {"operation=create", "apiflag=api", "policyType=Config"}, requestID, "Config");
2475 * Create Config Policy API Implementation
2477 public String updateConfigPolicy(String policyName, String policyDescription, String ecompName, String configName,
2478 Map<String, String> configAttributes, String configType, String body, String policyScope, UUID requestID,
2479 String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2480 return updateConfigPolicy(policyName, policyDescription, ecompName, configName,
2481 configAttributes, configType, body, policyScope, requestID, userName, pass, riskLevel, riskType, guard, ttlDate);
2484 public String updateConfigPolicy(String policyName, String policyDescription, String ecompName, String configName,
2485 Map<String, String> configAttributes, String configType, String body, String policyScope,
2486 UUID requestID, String userID, String passcode,String riskLevel, String riskType, String guard,
2487 String ttlDate) throws Exception {
2489 String response = null;
2490 String configBody = null;
2491 String resource= "updatePolicy";
2492 if(!checkPermissions(userID, passcode, resource)){
2493 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
2494 response = XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource;
2497 //check body for JSON form and remove single quotes if present
2498 if (configType.equalsIgnoreCase("JSON")) {
2499 if (body.contains("'")) {
2500 configBody = body.replace("'", "\"");
2508 boolean levelCheck = isNumeric(riskLevel);
2510 if (policyName==null||policyName.equalsIgnoreCase("")){
2511 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2512 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2513 } else if (ecompName==null||ecompName.equalsIgnoreCase("")){
2514 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.");
2515 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.";
2516 } else if (configName==null||configName.equalsIgnoreCase("")){
2517 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.");
2518 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Config Name given.";
2519 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2520 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2521 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2522 } else if (!levelCheck){
2523 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2524 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2527 //set values for basic policy information
2528 String policyType = "Config";
2529 String configPolicyType = "base";
2531 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(configPolicyType, policyName, policyDescription, ecompName, configName, configAttributes, configType,
2532 configBody, true, policyScope,0, riskLevel, riskType, guard, ttlDate);
2534 //send JSON object to PAP
2535 response = (String) callPAP(newPAPPolicy, new String[] {"operation=update", "apiflag=api", "policyType=" + policyType}, requestID, "Config");
2544 * Create Config Firewall Policy API implementation
2546 public String createConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID,
2547 String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2548 return createConfigFirewallPolicy(policyName, firewallJson, policyScope, requestID, userName, pass, riskLevel, riskType, guard, ttlDate);
2551 public String createConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, String userID, String passcode,
2552 String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2554 String response = null;
2555 String resource= "createPolicy";
2556 if(!checkPermissions(userID, passcode, resource)){
2557 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
2558 response = XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource;
2562 //set values for basic policy information
2563 String configName = firewallJson.get("configName").toString();
2564 //String configDescription = firewallJson.get("configDescription").toString();
2565 String configDescription = "";
2566 String json = firewallJson.toString();
2568 boolean levelCheck = isNumeric(riskLevel);
2570 if (!isJSONValid(json)) {
2571 logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Invalid JSON for firewallJson: " + json);
2572 throw new PolicyDecisionException(XACMLErrorConstants.ERROR_SCHEMA_INVALID + "Invalid JSON for firewallJson: " + json);
2575 if (policyName==null||policyName.equalsIgnoreCase("")){
2576 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2577 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2578 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2579 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2580 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2581 } else if (!levelCheck){
2582 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2583 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2586 StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Firewall Config", policyName, configDescription, configName, false, policyScope, json, 0,
2587 riskLevel, riskType, guard, ttlDate);
2589 //send JSON object to PAP
2590 response = (String) callPAP(newPAPPolicy, new String[] {"operation=create", "apiflag=api", "policyType=Config"}, requestID, "ConfigFirewall");
2597 * Update Config Firewall Policy API implementation
2599 public String updateConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, String riskLevel, String riskType,
2600 String guard, String ttlDate) throws Exception {
2601 return updateConfigFirewallPolicy(policyName, firewallJson, policyScope, requestID, userName, pass, riskLevel, riskType, guard, ttlDate);
2604 public String updateConfigFirewallPolicy(String policyName, JsonObject firewallJson, String policyScope, UUID requestID, String userID, String passcode,
2605 String riskLevel, String riskType, String guard, String ttlDate) throws Exception {
2607 String response = null;
2608 String resource= "updatePolicy";
2609 if(!checkPermissions(userID, passcode, resource)){
2610 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
2611 response = XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource;
2614 String configName = firewallJson.get("configName").toString();
2615 //String configDescription = firewallJson.get("configDescription").toString();
2616 String configDescription = ""; //ASK Lak about this...****
2617 String json = firewallJson.toString();
2618 boolean levelCheck = isNumeric(riskLevel);
2620 if (policyName==null||policyName.equalsIgnoreCase("")){
2621 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2622 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2623 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2624 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2625 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2626 } else if (!levelCheck){
2627 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2628 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2631 StdPAPPolicy newPAPPolicy = new StdPAPPolicy("Firewall Config", policyName, configDescription, configName, true, policyScope, json, 0,
2632 riskLevel, riskType, guard, ttlDate);
2634 //send JSON object to PAP
2635 response = (String) callPAP(newPAPPolicy, new String[] {"operation=update", "apiflag=api", "policyType=Config"}, requestID, "ConfigFirewall");
2642 * Create or Update BRMS Raw Config Policy API implementation
2644 public String createUpdateBRMSRawPolicy(String policyName,
2645 String policyDescription,
2646 Map<AttributeType, Map<String, String>> dyanamicFieldConfigAttributes,
2656 String response = null;
2657 String operation = null;
2661 operation = "update";
2663 operation = "create";
2666 boolean levelCheck = isNumeric(riskLevel);
2668 if (policyName==null||policyName.equalsIgnoreCase("")){
2669 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2670 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2671 } else if(policyDescription==null || policyDescription.equalsIgnoreCase("")){
2672 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policyDescription given.");
2673 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No policyDescription given.";
2674 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2675 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2676 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2677 } else if (brmsRawBody==null ||brmsRawBody.equalsIgnoreCase("")){
2678 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No rule body given.");
2679 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No rule body given.";
2680 } else if (!levelCheck){
2681 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2682 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2684 /*String configPolicyType, String policyName, String description,
2685 String configName, Boolean editPolicy, String domain,
2686 Map<String,String> dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName,
2687 String configBodyData*/
2689 StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Raw",policyName,policyDescription,
2690 "BRMS_RAW_RULE",isEdit,policyScope,
2691 dyanamicFieldConfigAttributes.get(AttributeType.RULE), 0, "DROOLS",
2692 brmsRawBody, riskLevel, riskType, guard, ttlDate);
2694 //send JSON object to PAP
2696 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigBrmsRaw");
2697 } catch (Exception e) {
2698 // TODO Auto-generated catch block
2699 e.printStackTrace();
2707 * Create or Update BRMS Param Config Policy API implementation
2709 public String createUpdateBRMSParamPolicy(String policyName,
2710 String policyDescription,
2711 Map<AttributeType, Map<String, String>> dyanamicFieldConfigAttributes,
2716 Map<AttributeType, Map<String, String>> drlRuleAndUIParams,
2717 String riskLevel, String riskType, String guard, String ttlDate) {
2719 String response = null;
2720 String operation = null;
2724 operation = "update";
2726 operation = "create";
2729 boolean levelCheck = isNumeric(riskLevel);
2731 if (policyName==null||policyName.equalsIgnoreCase("")){
2732 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2733 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2734 } else if(policyDescription==null || policyDescription.equalsIgnoreCase("")){
2735 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No policyDescription given.");
2736 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No policyDescription given.";
2737 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2738 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2739 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2740 } else if ((dyanamicFieldConfigAttributes==null)){
2741 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Rule Attributes given.");
2742 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Rule Attributes given.";
2743 } else if (!levelCheck){
2744 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2745 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2747 /*public StdPAPPolicy (String configPolicyType, String policyName, String description,
2748 String configName, Boolean editPolicy, String domain,
2749 Map<String,String> dyanamicFieldConfigAttributes, Integer highestVersion, String eCompName,
2750 String configBodyData,Map<String,String> drlRuleAndUIParams) */
2752 StdPAPPolicy newPAPPolicy = new StdPAPPolicy("BRMS_Param",policyName,policyDescription,
2753 "BRMS_PARAM_RULE",isEdit,policyScope,
2754 drlRuleAndUIParams.get(AttributeType.MATCHING), 0, "DROOLS",
2755 brmsRawBody, drlRuleAndUIParams.get(AttributeType.RULE), riskLevel, riskType, guard, ttlDate);
2757 //send JSON object to PAP
2759 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigBrmsParam");
2760 } catch (Exception e) {
2761 // TODO Auto-generated catch block
2762 e.printStackTrace();
2770 * Create or Update Action Policy API implementation
2772 public String createUpdateActionPolicy(String policyName, String policyDescription, Map<String,String> componentAttributes, List<String> dynamicRuleAlgorithmLabels,
2773 List<String> dynamicRuleAlgorithmField1, List<String> dynamicRuleAlgorithmFunctions, List<String> dynamicRuleAlgorithmField2,
2774 String actionPerformer, String actionAttribute, String policyScope, Boolean isEdit, UUID requestID) {
2776 String response = null;
2777 String operation = null;
2780 operation = "update";
2782 operation = "create";
2785 if (policyName==null||policyName.equalsIgnoreCase("")){
2786 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2787 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2789 } else if (componentAttributes==null||componentAttributes.equals("")){
2790 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given.");
2791 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Component Attributes given.";
2793 } else if (actionAttribute==null||actionAttribute.equalsIgnoreCase("")){
2794 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Attribute given.");
2795 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Attribute given.";
2797 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2798 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2799 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2801 } else if (actionPerformer==null||actionPerformer.equalsIgnoreCase("")){
2802 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Performer given.");
2803 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Action Performer given.";
2805 } else if (!actionPerformer.equals("PEP")) {
2806 if (!actionPerformer.equals("PDP")) {
2807 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Performer given.");
2808 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Performer given.";
2813 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyDescription, componentAttributes, dynamicRuleAlgorithmLabels, dynamicRuleAlgorithmFunctions,
2814 dynamicRuleAlgorithmField1, dynamicRuleAlgorithmField2, actionPerformer, actionAttribute, isEdit, policyScope, 0);
2816 //send JSON object to PAP
2818 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Action"}, requestID, "Action");
2819 } catch (Exception e) {
2820 // TODO Auto-generated catch block
2821 e.printStackTrace();
2829 * Create or Update Decision Policy implementation
2831 private String createUpdateDecisionPolicy(String policyName, String policyDescription, String ecompName, RuleProvider ruleProvider, Map<String,String> componentAttributes, Map<String,String> settings,
2832 List<String> dynamicRuleAlgorithmLabels, List<String> dynamicRuleAlgorithmField1, List<String> dynamicRuleAlgorithmFunctions, List<String> dynamicRuleAlgorithmField2,
2833 String policyScope, Boolean isEdit, UUID requestID) {
2835 String response = null;
2836 String operation = null;
2839 operation = "update";
2841 operation = "create";
2844 if (policyName==null||policyName.equalsIgnoreCase("")){
2845 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2846 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2847 } else if (ecompName==null||ecompName.equalsIgnoreCase("")){
2848 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.");
2849 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No ECOMP Name given.";
2850 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2851 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2852 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2855 if (ruleProvider==null) {
2856 ruleProvider = RuleProvider.CUSTOM ;
2859 StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyName, policyDescription, ecompName, ruleProvider.toString(), componentAttributes, settings, dynamicRuleAlgorithmLabels, dynamicRuleAlgorithmFunctions,
2860 dynamicRuleAlgorithmField1, dynamicRuleAlgorithmField2, null, null, null, isEdit, policyScope, 0);
2862 //send JSON object to PAP
2864 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Decision"}, requestID, "Decision");
2865 } catch (Exception e) {
2866 // TODO Auto-generated catch block
2867 e.printStackTrace();
2875 * Create or Update ClosedLoop_Fault policy implementation
2877 private String createUpdateClosedLoopPolicy(String policyName, JsonObject configBody, String policyDescription, String policyScope, Boolean isEdit,
2878 UUID requestID,String riskLevel, String riskType, String guard, String ttlDate) {
2880 String response = null;
2881 String operation = null;
2882 String oldPolicyName = null;
2885 operation = "update";
2886 if (policyName.endsWith("_Draft")) {
2887 oldPolicyName = policyName + "_Draft.1";
2890 operation = "create";
2893 boolean levelCheck = isNumeric(riskLevel);
2895 // get values and attributes from the JsonObject
2896 String ecompName = configBody.get("ecompname").toString().replace("\"", "");
2897 String jsonBody = configBody.toString();
2900 if (policyName==null||policyName.equalsIgnoreCase("")){
2901 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2902 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2903 } else if (ecompName==null||ecompName.equals("")){
2904 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.");
2905 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.";
2906 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2907 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2908 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2909 } else if (!levelCheck){
2910 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2911 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2915 StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_Fault", policyName, policyDescription, ecompName,
2916 jsonBody, false, oldPolicyName, null, isEdit, policyScope, 0, riskLevel, riskType, guard, ttlDate);
2918 //send JSON object to PAP
2920 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigClosedLoop");
2921 } catch (Exception e) {
2922 // TODO Auto-generated catch block
2923 e.printStackTrace();
2931 private String createUpdateClosedLoopPmPolicy(String policyName, JsonObject configBody, String policyDescription, String policyScope, Boolean isEdit,
2932 UUID requestID, String riskLevel, String riskType, String guard, String ttlDate) {
2934 String response = null;
2935 String operation = null;
2936 String oldPolicyName = null;
2939 operation = "update";
2941 operation = "create";
2944 boolean levelCheck = isNumeric(riskLevel);
2946 // get values and attributes from the JsonObject
2947 String ecompName = configBody.get("ecompname").toString().replace("\"", "");
2948 String serviceType = configBody.get("serviceTypePolicyName").toString().replace("\"", "");
2949 String jsonBody = configBody.toString();
2952 if (policyName==null||policyName.equalsIgnoreCase("")){
2953 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
2954 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
2955 } else if (ecompName==null||ecompName.equals("")){
2956 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.");
2957 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.";
2958 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
2959 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
2960 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
2961 } else if (!levelCheck){
2962 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
2963 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
2967 StdPAPPolicy newPAPPolicy = new StdPAPPolicy("ClosedLoop_PM", policyName, policyDescription, ecompName,
2968 jsonBody, false, oldPolicyName, serviceType, isEdit, policyScope, 0, riskLevel, riskType, guard, ttlDate);
2970 //send JSON object to PAP
2972 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigClosedLoop");
2973 } catch (Exception e) {
2974 // TODO Auto-generated catch block
2975 e.printStackTrace();
2983 public Boolean validateNONASCIICharactersAndAllowSpaces(Object json){
2984 Boolean isValidForm = false;
2985 if (json instanceof String) {
2986 String jsonString = (String)json;
2987 if (jsonString.isEmpty()) {
2988 logger.info("JSON String is empty so cannot validate NON ACSII Characters.");
2990 if(CharMatcher.ASCII.matchesAllOf((CharSequence) jsonString)){
2991 logger.info("The Value does not contain ASCII Characters");
2994 logger.error("The Value Contains Non ASCII Characters");
2995 isValidForm = false;
2998 } else if (json instanceof JsonObject) {
2999 JsonObject jsonObj = (JsonObject)json;
3000 if (jsonObj.isEmpty()){
3001 logger.info("JSON object is empty so cannot validate NON ACSII Characters.");
3003 if(CharMatcher.ASCII.matchesAllOf((CharSequence) jsonObj.toString())){
3004 logger.info("The Value does not contain ASCII Characters");
3007 logger.error("The Value Contains Non ASCII Characters");
3008 isValidForm = false;
3017 private String createUpdateMicroServicesPolicy(String policyName, JsonObject microServiceAttributes, String ecompName, String policyScope, Boolean isEdit, UUID requestID,
3018 String riskLevel, String riskType, String guard, String ttlDate) {
3020 String response = null;
3021 String operation = null;
3024 operation = "update";
3026 operation = "create";
3029 boolean levelCheck = isNumeric(riskLevel);
3031 // get values and attributes from the JsonObject
3032 String microService = microServiceAttributes.get("service").toString().replace("\"", "");
3033 String uuid = microServiceAttributes.get("uuid").toString().replace("\"", "");
3034 String msLocation = microServiceAttributes.get("location").toString().replace("\"", "");;
3035 String policyDescription = microServiceAttributes.get("description").toString().replace("\"", "");
3036 String configName = microServiceAttributes.get("configName").toString().replace("\"", "");
3037 String priority = microServiceAttributes.get("priority").toString().replace("\"", "");
3038 String version = microServiceAttributes.get("version").toString().replace("\"", "");
3041 if (policyName==null||policyName.equalsIgnoreCase("")){
3042 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
3043 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
3044 } else if (ecompName==null||ecompName.equals("")){
3045 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.");
3046 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Ecomp Name given.";
3047 } else if (configName==null||configName.equalsIgnoreCase("")){
3048 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Configuration Name given.");
3049 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Configuration Name given.";
3050 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
3051 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
3052 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
3053 } else if (!levelCheck){
3054 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.");
3055 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect Risk Level given.";
3059 StdPAPPolicy newPAPPolicy = new StdPAPPolicy("DCAE Micro Service", policyName, policyDescription, ecompName,
3060 configName, microService, uuid, msLocation, microServiceAttributes.toString(), priority,
3061 version, isEdit, policyScope, 0, riskLevel, riskType, guard, ttlDate);
3063 //send JSON object to PAP
3065 response = (String) callPAP(newPAPPolicy, new String[] {"operation="+operation, "apiflag=api", "policyType=Config"}, requestID, "ConfigMS");
3066 } catch (Exception e) {
3067 // TODO Auto-generated catch block
3068 e.printStackTrace();
3078 * Push a policy to the PDP API implementation
3080 public String pushPolicy(String policyScope, String policyName, String policyType, String pdpGroup, UUID requestID) throws Exception {
3081 return pushPolicy(policyScope, policyName, policyType, pdpGroup, requestID, userName, pass);
3084 public String pushPolicy(String policyScope, String policyName, String policyType, String pdpGroup, UUID requestID, String userID, String passcode) throws Exception {
3085 String resource= "pushPolicy";
3086 if(!checkPermissions(userID, passcode, resource)){
3087 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
3088 return (XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
3090 String response = null;
3091 String filePrefix = null;
3092 String clientScope = null;
3093 String activeVersion = null;
3095 //get the client scope based policy type
3096 if (policyType.equalsIgnoreCase("Firewall")){
3097 clientScope = "ConfigFirewall";
3098 filePrefix = "Config_FW_";
3099 } else if (policyType.equalsIgnoreCase("Action")) {
3100 clientScope = "Action";
3101 filePrefix = "Action_";
3102 } else if (policyType.equalsIgnoreCase("Decision")){
3103 clientScope = "Decision";
3104 filePrefix = "Decision_";
3105 } else if (policyType.equalsIgnoreCase("Base")){
3106 clientScope = "Config";
3107 filePrefix = "Config_";
3108 } else if (policyType.equalsIgnoreCase("ClosedLoop_Fault")){
3109 clientScope = "ConfigClosedLoop";
3110 filePrefix = "Config_Fault_";
3111 } else if (policyType.equalsIgnoreCase("ClosedLoop_PM")){
3112 clientScope = "ConfigClosedLoop";
3113 filePrefix = "Config_PM_";
3114 } else if (policyType.equalsIgnoreCase("MicroService")) {
3115 clientScope = "ConfigMS";
3116 filePrefix = "Config_MS_";
3117 }else if (policyType.equalsIgnoreCase("BRMS_RAW")){
3118 clientScope = "ConfigBrmsRaw";
3119 filePrefix = "Config_BRMS_Raw_";
3120 } else if (policyType.equalsIgnoreCase("BRMS_PARAM")){
3121 clientScope = "ConfigBrmsParam";
3122 filePrefix = "Config_BRMS_Param_";
3125 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + " is not a valid Policy Type.");
3126 return XACMLErrorConstants.ERROR_DATA_ISSUE + policyType + " is not a valid Policy Type.";
3129 logger.debug("clientScope is " + clientScope);
3130 logger.debug("filePrefix is " + filePrefix);
3132 if (pdpGroup == null) {
3133 pdpGroup = "default";
3136 if (policyName==null||policyName.equalsIgnoreCase("")){
3137 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
3138 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
3139 } else if (policyScope==null||policyScope.equalsIgnoreCase("")){
3140 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.");
3141 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Scope given.";
3142 } else if (policyType==null||policyType.equalsIgnoreCase("")){
3143 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Type given.");
3144 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Type given.";
3146 // requestID null check.
3147 if(requestID==null){
3148 requestID = UUID.randomUUID();
3149 logger.debug("Request ID not provided. Generating request ID " + requestID.toString());
3152 // change call to getActiveVersion to pass requestID for PAP to receive on the GET process so PAP won't generate another
3153 // activeVersion = getActiveVersion(policyScope, filePrefix, policyName, clientScope);
3154 activeVersion = getActiveVersion(policyScope, filePrefix, policyName, clientScope, requestID);
3155 logger.debug("The active version of " + policyScope + File.separator + filePrefix + policyName + " is " + activeVersion);
3158 if (activeVersion.equalsIgnoreCase("pe100")) {
3159 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! "
3160 + "\n Contact Administrator for this Scope. ");
3161 return XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is 403. PEP is not Authorized for making this Request!! "
3162 + "Contact Administrator for this Scope. ";
3164 } else if (activeVersion.equalsIgnoreCase("pe300")) {
3165 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. "
3166 + "This indicates a problem with getting the version from the PAP or the policy does not exist.");
3167 return XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is 404. "
3168 + "This indicates a problem with getting the version from the PAP or the policy does not exist.";
3172 if (!activeVersion.equalsIgnoreCase("0")) {
3173 id = policyScope + "." + filePrefix + policyName + "." + activeVersion + ".xml";
3174 logger.debug("The policyId is " + id);
3176 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. "
3177 + "This indicates the policy does not exist, please verify the policy exists.");
3178 return XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the activeVersion for this policy. could not retrieve the activeVersion for this policy. "
3179 + "This indicates the policy does not exist, please verify the policy exists.";
3182 // change call to getgitPath to pass requestID for PAP to receive on the GET process so PAP won't generate another
3183 // String gitPath = getGitPath(policyScope, filePrefix, policyName, activeVersion, clientScope);
3184 String gitPath = getGitPath(policyScope, filePrefix, policyName, activeVersion, clientScope, requestID);
3185 logger.debug("Full gitPath policy xml file: " + gitPath);
3187 // change call to getSelectedURI to pass requestID for PAP to receive on the GET process so PAP won't generate another
3188 // URI selectedURI = getSelectedURI(gitPath, clientScope);
3189 URI selectedURI = getSelectedURI(gitPath, clientScope, requestID);
3191 logger.debug("The selectedURI is : " + selectedURI.toString());
3192 String name = filePrefix+policyName;
3194 StdPDPPolicy selectedPolicy = new StdPDPPolicy(id, true, name, selectedURI, isValid, policyId, description, pushVersion);
3196 logger.debug("StdPDPPolicy object contains: " + selectedPolicy.getId() + ", " + selectedPolicy.getName() + ", " + selectedPolicy.getLocation().toString());
3198 response = copyPolicy(selectedPolicy, pdpGroup, clientScope, requestID);
3200 logger.debug("copyPolicy response: " + response);
3202 if(response.contains("successfully")){
3203 response = (String) callPAP(selectedPolicy, new String[]{"groupId=" + pdpGroup, "policyId="+id, "apiflag=addPolicyToGroup", "operation=PUT"}, requestID, clientScope);
3206 logger.debug("Final API response: " + response);
3213 private String deletePolicyFromPAP(DeletePolicyParameters parameters) {
3214 String response = null;
3215 String clientScope = null;
3216 String pdpGroup = parameters.getPdpGroup();
3218 if (pdpGroup==null){
3222 //get the client scope based policy type
3223 if (parameters.getPolicyName().contains("Config_FW")){
3224 clientScope = "ConfigFirewall";
3225 } else if (parameters.getPolicyName().contains("Action")) {
3226 clientScope = "Action";
3227 } else if (parameters.getPolicyName().contains("Decision")){
3228 clientScope = "Decision";
3229 } else if (parameters.getPolicyName().contains("Config_Fault")){
3230 clientScope = "ConfigClosedLoop";
3231 } else if (parameters.getPolicyName().contains("Config_PM")){
3232 clientScope = "ConfigClosedLoop";
3233 } else if (parameters.getPolicyName().contains("Config_MS")){
3234 clientScope = "ConfigMS";
3235 } else if (parameters.getPolicyName().contains("Config_BRMS_Raw")){
3236 clientScope = "ConfigBrmsRaw";
3237 } else if (parameters.getPolicyName().contains("Config_BRMS_Param")){
3238 clientScope = "ConfigBrmsParam";
3240 clientScope = "Config";
3243 logger.debug("clientScope is " + clientScope);
3245 if (clientScope==null||clientScope.equals("")){
3246 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + parameters.getPolicyName() + " is not a valid Policy Name.");
3247 return XACMLErrorConstants.ERROR_DATA_ISSUE + parameters.getPolicyName() + " is not a valid Policy Name.";
3250 if (parameters.getPolicyName()==null||parameters.getPolicyName().equalsIgnoreCase("")){
3251 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
3252 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
3253 } else if (parameters.getDeleteCondition()==null||parameters.getDeleteCondition().equals("")){
3254 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given.");
3255 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Delete Condition given.";
3258 StdPAPPolicy deletePapPolicy = new StdPAPPolicy(parameters.getPolicyName(), parameters.getDeleteCondition().toString());
3260 //send JSON object to PAP
3262 response = (String) callPAP(deletePapPolicy, new String[] {"groupId="+pdpGroup, "apiflag=deletePapApi", "operation=delete" }, parameters.getRequestID(), clientScope);
3263 } catch (Exception e) {
3264 // TODO Auto-generated catch block
3265 e.printStackTrace();
3273 private String deletePolicyFromPDP(DeletePolicyParameters parameters) {
3274 String response = null;
3275 String clientScope = null;
3276 String pdpGroup = parameters.getPdpGroup();
3278 if (pdpGroup==null){
3282 //get the client scope based policy type
3283 if (parameters.getPolicyName().contains("Config_FW")){
3284 clientScope = "ConfigFirewall";
3285 } else if (parameters.getPolicyName().contains("Action")) {
3286 clientScope = "Action";
3287 } else if (parameters.getPolicyName().contains("Decision")){
3288 clientScope = "Decision";
3289 } else if (parameters.getPolicyName().contains("Config_Fault")){
3290 clientScope = "ConfigClosedLoop";
3291 } else if (parameters.getPolicyName().contains("Config_PM")){
3292 clientScope = "ConfigClosedLoop";
3293 } else if (parameters.getPolicyName().contains("Config_MS")){
3294 clientScope = "ConfigMS";
3295 }else if (parameters.getPolicyName().contains("Config_BRMS_Raw")){
3296 clientScope = "ConfigBrmsRaw";
3297 } else if (parameters.getPolicyName().contains("Config_BRMS_Param")){
3298 clientScope = "ConfigBrmsParam";
3300 clientScope = "Config";
3303 logger.debug("clientScope is " + clientScope);
3305 if (clientScope==null||clientScope.equals("")){
3306 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + parameters.getPolicyName() + " is not a valid Policy Name.");
3307 return XACMLErrorConstants.ERROR_DATA_ISSUE + parameters.getPolicyName() + " is not a valid Policy Name.";
3310 if (parameters.getPolicyName()==null||parameters.getPolicyName().equalsIgnoreCase("")){
3311 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.");
3312 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No Policy Name given.";
3313 } else if (parameters.getPdpGroup()==null||parameters.getPdpGroup().equals("")){
3314 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given.");
3315 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "No PDP Group given.";
3318 //send JSON object to PAP
3320 response = (String) callPAP(null, new String[] {"policyName="+parameters.getPolicyName(), "groupId="+pdpGroup, "apiflag=deletePdpApi", "operation=delete" }, parameters.getRequestID(), clientScope);
3321 } catch (Exception e) {
3322 // TODO Auto-generated catch block
3323 e.printStackTrace();
3332 * Copy a single Policy file from the input stream to the PAP Servlet.
3333 * Either this works (silently) or it throws an exception.
3336 public String copyFile(String policyId, String group, StdPAPPolicy location, String clientScope, UUID requestID) throws PAPException {
3337 String response = null;
3338 //String clientScope = null;
3340 // send the policy file to the PAP Servlet
3342 response = (String) callPAP(location, new String[] {"groupId=" + group, "policyId="+policyId, "apiflag=api", "operation=post"}, requestID, clientScope);
3343 } catch (Exception e) {
3344 String message = "Unable to PUT policy '" + policyId + "', e:" + e;
3345 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
3346 throw new PAPException(message);
3352 public String copyPolicy(PDPPolicy policy, String group, String policyType, UUID requestID) throws PAPException {
3353 String response = null;
3355 if (policy == null || group == null) {
3356 throw new PAPException("Null input policy="+policy+" group="+group);
3359 StdPAPPolicy location = new StdPAPPolicy(policy.getLocation());
3360 response = copyFile(policy.getId(), group, location, policyType, requestID);
3361 } catch (Exception e) {
3362 String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e;
3363 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e);
3364 throw new PAPException(message);
3370 public Object callPAP(Object content, String[] parameters, UUID requestID, String clientScope) throws Exception {
3371 String response = null;
3372 HttpURLConnection connection = null;
3373 String requestMethod = null;
3374 String operation = null;
3376 // Checking for the available PDPs is done during the first Request and the List is going to have the connected PDP as first element.
3377 // This makes it Real-Time to change the list depending on their availability.
3378 if (paps == null || paps.isEmpty()) {
3379 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
3380 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
3383 boolean connected = false;
3384 while (papsCount < paps.size()) {
3386 String fullURL = paps.get(0);
3387 if (parameters != null && parameters.length > 0) {
3388 String queryString = "";
3389 for (String p : parameters) {
3390 queryString += "&" + p;
3391 if (p.equalsIgnoreCase("operation=post")){
3392 requestMethod = "POST";
3393 } else if (p.equalsIgnoreCase("operation=delete")){
3394 requestMethod = "DELETE";
3395 operation = "delete";
3397 requestMethod = "PUT";
3398 if (p.equalsIgnoreCase("operation=create")){
3399 operation = "create";
3400 } else if (p.equalsIgnoreCase("operation=update")){
3401 operation = "update";
3402 } else if (p.equalsIgnoreCase("operation=createDictionary")){
3403 operation = "createDictionary";
3407 fullURL += "?" + queryString.substring(1);
3410 URL url = new URL (fullURL);
3412 //Open the connection
3413 connection = (HttpURLConnection)url.openConnection();
3415 // Setting Content-Type
3416 connection.setRequestProperty("Content-Type",
3417 "application/json");
3419 // Adding Authorization
3420 connection.setRequestProperty("Authorization", "Basic "
3421 + encodingPAP.get(0));
3423 connection.setRequestProperty("Environment", environment);
3424 connection.setRequestProperty("ClientScope", clientScope);
3426 //set the method and headers
3427 connection.setRequestMethod(requestMethod);
3428 connection.setUseCaches(false);
3429 connection.setInstanceFollowRedirects(false);
3430 connection.setDoOutput(true);
3431 connection.setDoInput(true);
3433 if (requestID == null) {
3434 requestID = UUID.randomUUID();
3435 logger.info("No request ID provided, sending generated ID: " + requestID.toString());
3437 logger.info("Using provided request ID: " + requestID.toString());
3439 connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
3441 if (content != null) {
3442 if (content instanceof InputStream) {
3444 //send current configuration
3445 try (OutputStream os = connection.getOutputStream()) {
3446 int count = IOUtils.copy((InputStream)content, os);
3447 if (logger.isDebugEnabled()) {
3448 logger.debug("copied to output, bytes=" + count);
3451 } catch (Exception e) {
3452 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to write content in 'PUT'", e);
3456 // the content is an object to be encoded in JSON
3457 ObjectMapper mapper = new ObjectMapper();
3459 mapper.writeValue(connection.getOutputStream(), content);
3465 connection.connect();
3466 responseCode = connection.getResponseCode();
3467 // If Connected to PAP then break from the loop and continue with the Request
3468 if (connection.getResponseCode() > 0 || junit) {
3473 logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
3475 } catch (Exception e) {
3476 // This means that the PAP is not working
3481 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
3488 logger.debug("connected to the PAP : " + paps.get(0));
3489 logger.debug("--- Response: ---");
3490 Map<String, List<String>> headers = connection.getHeaderFields();
3491 for (String key : headers.keySet()) {
3492 logger.debug("Header :" + key + " Value: " + headers.get(key));
3495 if (responseCode == 200 || junit) {
3497 // Check for successful creation of policy
3498 String isSuccess = null;
3499 if(!junit){ //is this a junit test?
3500 isSuccess = connection.getHeaderField("successMapKey");
3501 operation = connection.getHeaderField("operation");
3503 isSuccess = "success";
3506 if (isSuccess.equals("success")) {
3507 if (operation.equals("update")) {
3508 logger.info("Transaction ID: " + requestID + " --Policy Updated Successfully!" );
3509 response = "Transaction ID: " + requestID + " --Policy with the name " + connection.getHeaderField("policyName") + " was successfully updated.";
3510 } else if (operation.equals("delete")) {
3511 logger.info("Transaction ID: " + requestID + " --Policy Deleted Successfully!");
3512 response = "Transaction ID: " + requestID + " --The policy was successfully deleted.";
3513 } else if (operation.equals("import")) {
3514 logger.info("Transaction ID: " + requestID + " --Policy Engine Import Successful!");
3515 response = "Transaction ID: " + requestID + " --The policy engine import for " + connection.getHeaderField("service") + " was successfull.";
3517 logger.info("Transaction ID: " + requestID + " --Policy Created Successfully!" );
3518 response = "Transaction ID: " + requestID + " --Policy with the name " + connection.getHeaderField("policyName") + " was successfully created.";
3522 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to Create/Update the Policy!");
3523 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Unable to Create/Update the Policy!";
3525 } else if (connection.getResponseCode() == 202) {
3526 if (connection.getHeaderField("operation")!=null && connection.getHeaderField("operation").equalsIgnoreCase("delete")){
3527 if (connection.getHeaderField("lockdown")!=null && connection.getHeaderField("lockdown").equals("true")){
3528 logger.warn("Transaction ID: " + requestID + "Policies are locked down.");
3529 response = "Transaction ID: " + requestID + " --Policies are locked down, please try again later.";
3532 } else if (connection.getResponseCode() == 204) {
3533 if (connection.getHeaderField("operation")!=null && connection.getHeaderField("operation").equals("push")){
3534 logger.info("Transaction ID: " + requestID + " --Policy '" + connection.getHeaderField("policyId") +
3535 "' was successfully pushed to the PDP group '" + connection.getHeaderField("groupId") + "'.");
3536 response = "Transaction ID: " + requestID + " --Policy '" + connection.getHeaderField("policyId") +
3537 "' was successfully pushed to the PDP group '" + connection.getHeaderField("groupId") + "'.";
3539 } else if (connection.getResponseCode() == 400 && connection.getHeaderField("error")!=null){
3540 if (connection.getHeaderField("error").equals("noPolicyExist")) {
3541 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.");
3542 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy does not exist on the PDP.";
3543 } else if (connection.getHeaderField("error").equals("invalidPolicyName")) {
3544 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
3545 + "policyName must be the full name of the file to be deleted including version and extension");
3546 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid policyName... "
3547 + "policyName must be the full name of the file to be deleted including version and extension";
3548 } else if (connection.getHeaderField("error").equals("actionPolicyDB")){
3549 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + connection.getHeaderField("actionAttribute") + " in the ActionPolicyDict table.");
3550 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid actionAttribute given.";
3551 } else if (connection.getHeaderField("error").equals("serviceModelDB")){
3552 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Service or Version. The Service Model, "
3553 + connection.getHeaderField("modelName") + " of version " + connection.getHeaderField("modelVersion")
3554 + " was not found in the dictionary.");
3555 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Service or Version. The Service Model, "
3556 + connection.getHeaderField("modelName") + " of version " + connection.getHeaderField("modelVersion")
3557 + " was not found in the dictionary.";
3558 } else if (connection.getHeaderField("error").equals("FWDBError")){
3559 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error when inserting Firewall ConfigBody data into database.");
3560 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error when inserting Firewall ConfigBody data into the database.";
3561 } else if (connection.getHeaderField("error").equals("savePolicy")){
3562 logger.error(connection.getHeaderField("message"));
3563 response = connection.getHeaderField("message");
3565 } else if (connection.getResponseCode() == 403) {
3566 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is "
3567 + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ");
3568 response = XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is "
3569 + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ";
3570 } else if (connection.getResponseCode() == 404 && connection.getHeaderField("error")!=null) {
3571 if (connection.getHeaderField("error").equals("unknownGroupId")){
3572 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message"));
3573 response = XACMLErrorConstants.ERROR_DATA_ISSUE + connection.getHeaderField("message") +
3574 " Please check the pdpGroup you are requesting to move the policy to.";
3576 } else if (connection.getResponseCode() == 409 && connection.getHeaderField("error")!=null) {
3577 if (connection.getHeaderField("error").equals("modelExistsDB")) {
3578 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Import Value Exist Error");
3579 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Import Value Exist Error: The import value "+connection.getHeaderField("service")+" already exist on the PAP. "
3580 + "Please create a new import value.";
3581 }else if (connection.getHeaderField("error").equals("policyExists")){
3582 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Exist Error");
3583 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Policy Exist Error: The Policy "+connection.getHeaderField("policyName")+" already exist on the PAP. "
3584 + "Please create a new policy or use the update API to modify the existing one.";
3586 } else if (connection.getResponseCode() == 500 && connection.getHeaderField("error")!=null) {
3587 if (connection.getHeaderField("error").equals("jpautils")){
3588 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Could not create JPAUtils instance on the PAP");
3589 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Could not create JPAUtils instance on the PAP";
3590 } else if (connection.getHeaderField("error").equals("deleteDB")){
3591 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to delete Policy from database.");
3592 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Failed to delete Policy from database.";
3593 } else if (connection.getHeaderField("error").equals("deleteFile")){
3594 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file.");
3595 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file";
3596 } else if (connection.getHeaderField("error").equals("groupUpdate")){
3597 logger.error(connection.getHeaderField("message"));
3598 response = connection.getHeaderField("message");
3599 }else if (connection.getHeaderField("error").equals("unknown")){
3600 logger.error(XACMLErrorConstants.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.");
3601 response = XACMLErrorConstants.ERROR_UNKNOWN + "Failed to delete the policy for an unknown reason. Check the file system and other logs for further information.";
3602 } else if (connection.getHeaderField("error").equals("deleteConfig")){
3603 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the configuration or action body file in specified location");
3604 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the configuration or action body file in specified location.";
3605 }else if (connection.getHeaderField("error").equals("missing")){
3606 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to create value in database because service does match a value in file");
3607 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Failed to create value in database because service does match a value in file";
3608 }else if (connection.getHeaderField("error").equals("importDB")){
3609 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Database errors during policy engine import");
3610 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "Database errors during policy engine import";
3611 }else if (connection.getHeaderField("error").equals("policyCopyError")){
3612 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + connection.getHeaderField("message"));
3613 response = XACMLErrorConstants.ERROR_PROCESS_FLOW + connection.getHeaderField("message");
3614 }else if (connection.getHeaderField("error").equals("addGroupError")){
3615 logger.error(connection.getHeaderField("message"));
3616 response = connection.getHeaderField("message");
3617 }else if (connection.getHeaderField("error").equals("error")){
3618 logger.error(XACMLErrorConstants.ERROR_UNKNOWN + "Could not create or update the policy for and unknown reason");
3619 response = XACMLErrorConstants.ERROR_UNKNOWN + "Could not create or update the policy for and unknown reason";
3622 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect.");
3623 response = XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while attempting perform this operation.. the request may be incorrect.";
3625 } catch (IOException e) {
3626 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
3627 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + e;
3628 throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"ERROR in connecting to the PAP ", e);
3632 response = "success";
3637 response = XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps;
3644 // change getSelectedURI method to receive requestID to be used to send to PAP on the GET request so PAP won't generate another
3645 // private URI getSelectedURI(String gitPath, String clientScope){
3646 private URI getSelectedURI(String gitPath, String clientScope, UUID requestID){
3647 //Connect to the PAP
3648 URI selectedURI = null;
3649 HttpURLConnection connection = null;
3650 String [] parameters = {"apiflag=uri", "gitPath="+gitPath};
3653 // Checking for the available PDPs is done during the first Request and the List is going to have the connected PDP as first element.
3654 // This makes it Real-Time to change the list depending on their availability.
3655 if (paps == null || paps.isEmpty()) {
3656 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
3658 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
3659 } catch (Exception e) {
3660 logger.error(e.getMessage());
3664 boolean connected = false;
3665 while (papsCount < paps.size()) {
3667 String fullURL = paps.get(0);
3668 if (parameters != null && parameters.length > 0) {
3669 String queryString = "";
3670 for (String p : parameters) {
3671 queryString += "&" + p;
3673 fullURL += "?" + queryString.substring(1);
3676 URL url = new URL (fullURL);
3678 //Open the connection
3679 connection = (HttpURLConnection)url.openConnection();
3681 // Setting Content-Type
3682 connection.setRequestProperty("Content-Type",
3683 "application/json");
3685 // Adding Authorization
3686 connection.setRequestProperty("Authorization", "Basic "
3687 + encodingPAP.get(0));
3689 connection.setRequestProperty("Environment", environment);
3690 connection.setRequestProperty("ClientScope", clientScope);
3692 //set the method and headers
3693 connection.setRequestMethod("GET");
3694 connection.setUseCaches(false);
3695 connection.setInstanceFollowRedirects(false);
3696 connection.setDoOutput(true);
3697 connection.setDoInput(true);
3699 // set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
3700 connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
3703 connection.connect();
3704 responseCode = connection.getResponseCode();
3705 // If Connected to PAP then break from the loop and continue with the Request
3706 if (connection.getResponseCode() > 0) {
3711 logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
3713 } catch (Exception e) {
3714 // This means that the PAP is not working
3715 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
3722 logger.debug("connected to the PAP : " + paps.get(0));
3723 logger.debug("--- Response: ---");
3724 Map<String, List<String>> headers = connection.getHeaderFields();
3725 for (String key : headers.keySet()) {
3726 logger.debug("Header :" + key + " Value: " + headers.get(key));
3729 if (connection.getResponseCode() == 200) {
3730 // Check for successful creation of policy
3731 String uri = connection.getHeaderField("selectedURI");
3732 logger.debug("URI from Header: " + uri);
3733 if (uri != null && !uri.equalsIgnoreCase("")) {
3734 selectedURI = URI.create(uri);
3737 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
3739 } else if (connection.getResponseCode() == 404) {
3740 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is "
3741 + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP");
3743 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST: Error occured while getting the gitPath from the PAP. The request may be incorrect.");
3745 } catch (IOException e) {
3746 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
3748 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
3749 } catch (Exception e1) {
3750 logger.error(e1.getMessage());
3755 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
3757 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
3758 } catch (Exception e) {
3759 logger.error(e.getMessage());
3767 // Make a call to the PAP to get the gitPath
3768 // change getGitPath method to receive requestID to be used to send to PAP on the GET request so PAP won't generate another
3769 // private String getGitPath(String policyScope, String filePrefix, String policyName, String activeVersion, String clientScope){
3770 private String getGitPath(String policyScope, String filePrefix, String policyName, String activeVersion, String clientScope, UUID requestID){
3772 //Connect to the PAP
3773 String gitPath = null;
3774 HttpURLConnection connection = null;
3775 String [] parameters = {"apiflag=gitPath", "policyScope="+policyScope, "filePrefix="+filePrefix,
3776 "policyName="+policyName, "activeVersion="+activeVersion};
3779 // Checking for the available PDPs is done during the first Request and the List is going to have the connected PDP as first element.
3780 // This makes it Real-Time to change the list depending on their availability.
3781 if (paps == null || paps.isEmpty()) {
3782 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
3784 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
3785 } catch (Exception e) {
3786 logger.error(e.getMessage());
3790 boolean connected = false;
3791 while (papsCount < paps.size()) {
3793 String fullURL = paps.get(0);
3794 if (parameters != null && parameters.length > 0) {
3795 String queryString = "";
3796 for (String p : parameters) {
3797 queryString += "&" + p;
3799 fullURL += "?" + queryString.substring(1);
3802 URL url = new URL (fullURL);
3804 //Open the connection
3805 connection = (HttpURLConnection)url.openConnection();
3807 // Setting Content-Type
3808 connection.setRequestProperty("Content-Type",
3809 "application/json");
3811 // Adding Authorization
3812 connection.setRequestProperty("Authorization", "Basic "
3813 + encodingPAP.get(0));
3815 connection.setRequestProperty("Environment", environment);
3816 connection.setRequestProperty("ClientScope", clientScope);
3818 //set the method and headers
3819 connection.setRequestMethod("GET");
3820 connection.setUseCaches(false);
3821 connection.setInstanceFollowRedirects(false);
3822 connection.setDoOutput(true);
3823 connection.setDoInput(true);
3825 // set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
3826 connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
3829 connection.connect();
3831 // If Connected to PAP then break from the loop and continue with the Request
3832 if (connection.getResponseCode() > 0) {
3837 logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
3839 } catch (Exception e) {
3840 // This means that the PAP is not working
3841 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
3848 logger.debug("connected to the PAP : " + paps.get(0));
3849 logger.debug("--- Response: ---");
3850 Map<String, List<String>> headers = connection.getHeaderFields();
3851 for (String key : headers.keySet()) {
3852 logger.debug("Header :" + key + " Value: " + headers.get(key));
3855 if (connection.getResponseCode() == 200) {
3856 // Check for successful creation of policy
3857 gitPath = connection.getHeaderField("gitPath");
3858 this.policyId = connection.getHeaderField("policyId");
3859 this.description = connection.getHeaderField("description");
3860 this.pushVersion = connection.getHeaderField("version");
3861 String isValid = connection.getHeaderField("isValid");
3862 this.isValid = Boolean.parseBoolean(isValid);
3864 logger.debug("GitPath from Header: " + gitPath);
3865 logger.debug("policyId from Header: " + policyId);
3866 logger.debug("description from Header: " + description);
3867 logger.debug("version from Header: " + pushVersion);
3868 logger.debug("isValid from Header: " + isValid);
3870 if (gitPath != null && !gitPath.equalsIgnoreCase("")) {
3873 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "could not retrieve the gitPath from the PAP");
3875 } else if (connection.getResponseCode() == 404) {
3876 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "response code of the URL is "
3877 + connection.getResponseCode() + ". This indicates a problem with getting the gitPath from the PAP");
3879 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "BAD REQUEST: Error occured while getting the gitPath from the PAP. The request may be incorrect.");
3881 } catch (IOException e) {
3882 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
3884 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
3885 } catch (Exception e1) {
3886 logger.error(e1.getMessage());
3891 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
3893 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
3894 } catch (Exception e) {
3895 logger.error(e.getMessage());
3903 // change getActiveVersion method to receive requestID to be used to send to PAP on the GET request so PAP won't generate another
3904 // private String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope) {
3905 private String getActiveVersion(String policyScope, String filePrefix, String policyName, String clientScope, UUID requestID) {
3907 //Connect to the PAP
3908 String version = null;
3909 HttpURLConnection connection = null;
3910 String [] parameters = {"apiflag=version","policyScope="+policyScope, "filePrefix="+filePrefix, "policyName="+policyName};
3913 // Checking for the available PDPs is done during the first Request and the List is going to have the connected PDP as first element.
3914 // This makes it Real-Time to change the list depending on their availability.
3915 if (paps == null || paps.isEmpty()) {
3916 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "PAPs List is Empty.");
3918 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"PAPs List is empty.");
3919 } catch (Exception e) {
3920 logger.error(e.getMessage());
3924 boolean connected = false;
3925 while (papsCount < paps.size()) {
3927 String fullURL = paps.get(0);
3928 if (parameters != null && parameters.length > 0) {
3929 String queryString = "";
3930 for (String p : parameters) {
3931 queryString += "&" + p;
3933 fullURL += "?" + queryString.substring(1);
3936 URL url = new URL (fullURL);
3938 //Open the connection
3939 connection = (HttpURLConnection)url.openConnection();
3941 // Setting Content-Type
3942 connection.setRequestProperty("Content-Type",
3943 "application/json");
3945 // Adding Authorization
3946 connection.setRequestProperty("Authorization", "Basic "
3947 + encodingPAP.get(0));
3949 connection.setRequestProperty("Environment", environment);
3950 connection.setRequestProperty("ClientScope", clientScope);
3953 //set the method and headers
3954 connection.setRequestMethod("GET");
3955 connection.setUseCaches(false);
3956 connection.setInstanceFollowRedirects(false);
3957 connection.setDoOutput(true);
3958 connection.setDoInput(true);
3960 // set requestID in header properties to be used to send to PAP on the GET request so PAP won't generate another
3961 connection.setRequestProperty("X-ECOMP-RequestID", requestID.toString());
3964 connection.connect();
3966 // If Connected to PAP then break from the loop and continue with the Request
3967 if (connection.getResponseCode() > 0) {
3972 logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error");
3974 } catch (Exception e) {
3975 // This means that the PAP is not working
3976 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP connection Error : " + e);
3983 logger.debug("connected to the PAP : " + paps.get(0));
3984 logger.debug("--- Response: ---");
3985 Map<String, List<String>> headers = connection.getHeaderFields();
3986 for (String key : headers.keySet()) {
3987 logger.debug("Header :" + key + " Value: " + headers.get(key));
3990 if (connection.getResponseCode() == 200) {
3991 // Check for successful creation of policy
3992 version = connection.getHeaderField("version");
3993 logger.debug("ActiveVersion from the Header: " + version);
3994 } else if (connection.getResponseCode() == 403) {
3995 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "response code of the URL is "
3996 + connection.getResponseCode() + ". PEP is not Authorized for making this Request!! \n Contact Administrator for this Scope. ");
3998 } else if (connection.getResponseCode() == 404) {
3999 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "response code of the URL is "
4000 + connection.getResponseCode() + ". This indicates a problem with getting the version from the PAP");
4003 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "BAD REQUEST: Error occured while getting the version from the PAP. The request may be incorrect.");
4005 } catch (IOException e) {
4006 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e);
4008 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ", e);
4009 } catch (Exception e1) {
4010 logger.error(e1.getMessage());
4015 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get valid response from PAP(s) " + paps);
4017 throw new Exception(XACMLErrorConstants.ERROR_DATA_ISSUE +"ERROR in connecting to the PAP ");
4018 } catch (Exception e) {
4019 logger.error(e.getMessage());
4026 // Validation for json inputs
4027 public static boolean isJSONValid(String data) {
4029 new JSONObject(data);
4030 InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8));
4031 JsonReader jsonReader = Json.createReader(stream);
4032 logger.debug("Json Value is: " + jsonReader.read().toString() );
4033 } catch (Exception e) {
4040 * Rotate the PDP list upon WEBsocket Failures
4042 public static void rotateList() {
4043 Collections.rotate(pdps, -1);
4044 Collections.rotate(encoding, -1);
4045 /* not required for 1510. //TODO uncomment when PAP API has been implemented
4046 * This Broke the PyPDP :( Since there is no PAP LIST yet.
4047 Collections.rotate(paps, -1);
4048 Collections.rotate(encodingPAP, -1);
4053 * Get the latest PDP
4055 public static String getPDPURL() {
4060 * Get the latest PAP
4062 public static String getPAPURL() {
4066 private JsonObject stringToJsonObject(String value) throws Exception{
4067 JsonReader jsonReader = Json.createReader(new StringReader(value));
4068 JsonObject object = jsonReader.readObject();
4073 private String getJsonResponseString() {
4074 String jsonString = "{\"Response\":[{\"Status\":{\"StatusCode\":{\"Value\":\"urn:oasis:names:tc:xacml:1.0:status:ok\"}},"
4075 + "\"AssociatedAdvice\":[{\"AttributeAssignment\":[{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\","
4076 + "\"Issuer\":\"\",\"AttributeId\":\"type\",\"Value\":\"Configuration\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},"
4077 + "{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"URLID\",\"Value\":"
4078 + "\"$URL/Config/JunitTest.Config_testing.1.json\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#anyURI\"},{\"Category\":"
4079 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"PolicyName\",\"Value\":"
4080 + "\"JunitTest.Config_testing.1.xml\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":"
4081 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"VersionNumber\",\"Value\":"
4082 + "\"1\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\","
4083 + "\"Issuer\":\"\",\"AttributeId\":\"matching:ECOMPName\",\"Value\":\"test\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},"
4084 + "{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"matching:ConfigName\","
4085 + "\"Value\":\"TestName\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":"
4086 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"matching:service\","
4087 + "\"Value\":\"ControllerServiceOpendcaeCapsuleServiceInstance\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},"
4088 + "{\"Category\":\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"matching:uuid\","
4089 + "\"Value\":\"TestUUID\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":"
4090 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"matching:Location\","
4091 + "\"Value\":\"Edge\",\"DataType\":\"http://www.w3.org/2001/XMLSchema#string\"},{\"Category\":"
4092 + "\"urn:oasis:names:tc:xacml:3.0:attribute-category:resource\",\"Issuer\":\"\",\"AttributeId\":\"Priority\",\"Value\":\"1\",\"DataType\":"
4093 + "\"http://www.w3.org/2001/XMLSchema#string\"}],\"Id\":\"MSID\"}],\"Decision\":\"Permit\"}]}";
4098 public PolicyChangeResponse policyEngineImport(ImportParameters importParameters) throws Exception {
4099 return policyEngineImport(importParameters, userName, pass);
4102 public PolicyChangeResponse policyEngineImport(ImportParameters importParameters, String userID, String passcode) throws Exception {
4103 StdPolicyChangeResponse response = new StdPolicyChangeResponse();
4104 String resource= "policyEngineImport";
4105 if(!checkPermissions(userID, passcode, resource)){
4106 logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
4107 response.setResponseMessage(XACMLErrorConstants.ERROR_PERMISSIONS + "You are not allowed to Make this Request. Please contact PolicyAdmin to give access to:" + resource);
4108 response.setResponseCode(401);
4111 InputStream targetStream = null;
4112 if(importParameters.getServiceName()!=null && importParameters.getVersion()!=null && importParameters.getServiceType()!=null){
4113 // This is Config Class Policy.
4114 if(importParameters.getFilePath()!=null){
4115 File input = new File(importParameters.getFilePath());
4116 if (input.getName().endsWith(".xmi") || input.getName().endsWith(".zip")){
4118 if (input.exists()){
4119 targetStream = new FileInputStream(input);
4121 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "File provided in ImportParameters does not exists.");
4122 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "File provided in ImportParameters does not exist.");
4125 } catch (Exception e) {
4126 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error reading in File");
4127 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error in reading in the file provided");
4130 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Data type.");
4131 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Incorrect File Type Given. Please use a file of type .xmi or .zip.");
4134 String[] parameters = new String[] {"importService=" + importParameters.getServiceType(), "serviceName="
4135 + importParameters.getServiceName(), "fileName=" + input.getName(), "version=" + importParameters.getVersion()};
4136 String responseMessage = (String) callPAP(targetStream, parameters, importParameters.getRequestID(), "importMS");
4137 response.setResponseMessage(responseMessage);
4139 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing required ImportParameters value.");
4140 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing required ImportParameters value.");
4143 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing required ImportParameters value.");
4144 response.setResponseMessage(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing required ImportParameters value.");
4150 * Give userID, Passcode and the Resoruce they are requesting for.
4152 private boolean checkPermissions(String userID, String passcode, String resource){
4153 Boolean result = false;
4154 if(pyPDPClientFile!=null){
4155 // Backward compatible pyPDP called us. So validate the user names and scope.
4156 Path clientPath = Paths.get(pyPDPClientFile);
4157 if (Files.notExists(clientPath)) {
4159 }else if(clientPath.toString().endsWith(".properties")) {
4161 HashMap<String, ArrayList<String>> clientMap = readProps(clientPath);
4162 if (clientMap.containsKey(userID) && clientMap.get(userID).get(0).equals(passcode)) {
4165 } catch (Exception e) {
4170 //Allowing Every Client who ever don't have access for AAF and Backup Client file
4176 private HashMap<String, ArrayList<String>> readProps(Path clientPath) throws Exception{
4178 Properties clientProp = new Properties();
4180 in = new FileInputStream(clientPath.toFile());
4181 clientProp.load(in);
4182 } catch (IOException e) {
4183 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
4184 throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Load the Properties file", e);
4186 // Read the Properties and Load the Clients and their scopes.
4187 HashMap<String, ArrayList<String>>clientMap = new HashMap<String, ArrayList<String>>();
4189 for (Object propKey : clientProp.keySet()) {
4190 String clientID = (String)propKey;
4191 String clientValue = clientProp.getProperty(clientID);
4192 if (clientValue != null) {
4193 if (clientValue.contains(",")) {
4194 ArrayList<String> clientValues = new ArrayList<String>(Arrays.asList(clientValue.split("\\s*,\\s*")));
4195 if(clientValues.get(0)!=null || clientValues.get(1)!=null || clientValues.get(0).isEmpty() || clientValues.get(1).isEmpty()){
4196 clientMap.put(clientID, clientValues);
4201 if (clientMap == null || clientMap.isEmpty()) {
4202 logger.debug(XACMLErrorConstants.ERROR_PERMISSIONS + "No Clients ID , Client Key and Scopes are available. Cannot serve any Clients !!");
4203 throw new Exception("Empty Client file");
4208 protected boolean isNumeric(String str)
4210 for (char c : str.toCharArray())
4212 if (!Character.isDigit(c)) return false;
4217 private String ConvertDate(Date date){
4218 String strDate = null;
4221 SimpleDateFormat dateformatJava = new SimpleDateFormat("dd-MM-yyyy");
4222 strDate = dateformatJava.format(date);