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=========================================================
21 package org.openecomp.policy.pap.xacml.rest.components;
23 import java.io.BufferedWriter;
25 import java.io.FileWriter;
26 import java.io.IOException;
27 import java.nio.file.Path;
28 import java.nio.file.Paths;
29 import java.util.HashMap;
30 import java.util.LinkedList;
31 import java.util.List;
34 import javax.persistence.EntityManager;
35 import javax.persistence.Query;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
53 import org.openecomp.policy.pap.xacml.rest.XACMLPapServlet;
54 import org.openecomp.policy.pap.xacml.rest.util.JPAUtils;
55 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
56 import org.openecomp.policy.rest.jpa.ActionPolicyDict;
57 import org.openecomp.policy.rest.jpa.Datatype;
58 import org.openecomp.policy.rest.jpa.FunctionDefinition;
59 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
60 import org.openecomp.policy.common.logging.eelf.MessageCodes;
61 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
62 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
63 import org.openecomp.policy.common.logging.flexlogger.Logger;
65 public class ActionPolicy extends Policy {
70 private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicy.class);
72 public static final String JSON_CONFIG = "JSON";
74 public static final String PDP_ACTION = "PDP";
75 public static final String PEP_ACTION = "PEP";
76 public static final String TYPE_ACTION = "REST";
78 public static final String GET_METHOD = "GET";
79 public static final String PUT_METHOD = "PUT";
80 public static final String POST_METHOD = "POST";
82 public static final String PERFORMER_ATTRIBUTEID = "performer";
83 public static final String TYPE_ATTRIBUTEID = "type";
84 public static final String METHOD_ATTRIBUTEID = "method";
85 public static final String HEADERS_ATTRIBUTEID = "headers";
86 public static final String URL_ATTRIBUTEID = "url";
87 public static final String BODY_ATTRIBUTEID = "body";
89 private static boolean isAttribute = false;
92 List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
93 List<String> dynamicFieldFunctionRuleAlgorithms = new LinkedList<>();
94 List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
95 List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
97 protected Map<String, String> dropDownMap = new HashMap<>();
100 public ActionPolicy() {
104 public ActionPolicy(PolicyRestAdapter policyAdapter){
105 this.policyAdapter = policyAdapter;
109 public Map<String, String> savePolicies() throws Exception {
111 Map<String, String> successMap = new HashMap<>();
112 if(isPolicyExists()){
113 successMap.put("EXISTS", "This Policy already exist on the PAP");
117 if(!ActionPolicy.isAttribute) {
118 successMap.put("invalidAttribute", "Action Attrbute was not in the database.");
122 if(!isPreparedToSave()){
123 //Prep and configure the policy for saving
127 // Until here we prepared the data and here calling the method to create xml.
128 Path newPolicyPath = null;
129 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
130 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() );
134 //This is the method for preparing the policy for saving. We have broken it out
135 //separately because the fully configured policy is used for multiple things
137 public boolean prepareToSave() throws Exception{
139 if(isPreparedToSave()){
140 //we have already done this
145 String policyID = policyAdapter.getPolicyID();
146 version = policyAdapter.getHighestVersion();
148 // Create the Instance for pojo, PolicyType object is used in marshalling.
149 if (policyAdapter.getPolicyType().equals("Action")) {
150 PolicyType policyConfig = new PolicyType();
152 policyConfig.setVersion(Integer.toString(version));
153 policyConfig.setPolicyId(policyID);
154 policyConfig.setTarget(new TargetType());
155 policyAdapter.setData(policyConfig);
158 policyName = policyAdapter.getNewFileName();
160 if (policyAdapter.getData() != null) {
161 // Action body is optional so checking value provided or not
162 String comboDictValue = policyAdapter.getActionAttribute();
163 String actionBody = getActionPolicyDict(comboDictValue).getBody();
164 if(!(actionBody==null || "".equals(actionBody))){
165 saveActionBody(policyName, actionBody);
168 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + comboDictValue + " in the ActionPolicyDict table.");
173 PolicyType actionPolicy = (PolicyType) policyAdapter.getData();
174 actionPolicy.setDescription(policyAdapter.getPolicyDescription());
175 actionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
177 AllOfType allOf = new AllOfType();
179 Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
181 // If there is any dynamic field attributes create the matches here
182 for (String keyField : dynamicFieldComponentAttributes.keySet()) {
183 String key = keyField;
184 String value = dynamicFieldComponentAttributes.get(key);
185 MatchType dynamicMatch = createDynamicMatch(key, value);
186 allOf.getMatch().add(dynamicMatch);
189 AnyOfType anyOf = new AnyOfType();
190 anyOf.getAllOf().add(allOf);
192 TargetType target = new TargetType();
193 target.getAnyOf().add(anyOf);
195 // Adding the target to the policy element
196 actionPolicy.setTarget(target);
198 RuleType rule = new RuleType();
199 rule.setRuleId(policyAdapter.getRuleID());
201 rule.setEffect(EffectType.PERMIT);
202 rule.setTarget(new TargetType());
204 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
205 dynamicFieldFunctionRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
206 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
207 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
208 //dropDownMap = policyAdapter.getDropDownMap();
209 dropDownMap = createDropDownMap();
211 // Rule attributes are optional and dynamic so check and add them to condition.
212 if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) {
213 boolean isCompound = false;
214 ConditionType condition = new ConditionType();
215 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
217 for (String labelAttr : dynamicLabelRuleAlgorithms) {
218 // if the rule algorithm as a label means it is a compound
219 if (dynamicFieldOneRuleAlgorithms.get(index).toString().equals(labelAttr)) {
220 ApplyType actionApply = new ApplyType();
222 String selectedFunction = (String) dynamicFieldFunctionRuleAlgorithms.get(index).toString();
223 String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString();
224 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
225 actionApply.setFunctionId(dropDownMap.get(selectedFunction));
226 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
227 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
228 condition.setExpression(new ObjectFactory().createApply(actionApply));
232 // if rule algorithm not a compound
234 condition.setExpression(new ObjectFactory().createApply(getInnerActionApply(dynamicLabelRuleAlgorithms.get(index).toString())));
236 rule.setCondition(condition);
238 // set the obligations to rule
239 rule.setObligationExpressions(getObligationExpressions());
240 actionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
241 policyAdapter.setPolicyData(actionPolicy);
243 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
246 setPreparedToSave(true);
250 // Saving the json Configurations file if exists at server location for action policy.
251 private void saveActionBody(String policyName, String actionBodyData) {
253 if(policyName.endsWith(".xml")){
254 policyName = policyName.replace(".xml", "");
256 File file = new File(ACTION_HOME+ File.separator + policyName + ".json");
257 FileWriter fw = new FileWriter(file.getAbsoluteFile());
258 BufferedWriter bw = new BufferedWriter(fw);
259 bw.write(actionBodyData);
261 if (LOGGER.isInfoEnabled()) {
262 LOGGER.info("Action Body is succesfully saved at " + file.getAbsolutePath());
264 } catch (IOException e) {
265 LOGGER.error("Exception Occured"+e);
269 // Data required for obligation part is setting here.
270 private ObligationExpressionsType getObligationExpressions() {
271 ObligationExpressionsType obligations = new ObligationExpressionsType();
273 ObligationExpressionType obligation = new ObligationExpressionType();
274 String comboDictValue = policyAdapter.getActionAttribute();
275 obligation.setObligationId(comboDictValue);
276 obligation.setFulfillOn(EffectType.PERMIT);
278 // Add Action Assignment:
279 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
280 assignment1.setAttributeId(PERFORMER_ATTRIBUTEID);
281 assignment1.setCategory(CATEGORY_RECIPIENT_SUBJECT);
283 AttributeValueType actionNameAttributeValue = new AttributeValueType();
284 actionNameAttributeValue.setDataType(STRING_DATATYPE);
285 actionNameAttributeValue.getContent().add(performer.get(policyAdapter.getActionPerformer()));
287 assignment1.setExpression(new ObjectFactory().createAttributeValue(actionNameAttributeValue));
288 obligation.getAttributeAssignmentExpression().add(assignment1);
290 // Add Type Assignment:
291 AttributeAssignmentExpressionType assignmentType = new AttributeAssignmentExpressionType();
292 assignmentType.setAttributeId(TYPE_ATTRIBUTEID);
293 assignmentType.setCategory(CATEGORY_RESOURCE);
295 AttributeValueType typeAttributeValue = new AttributeValueType();
296 typeAttributeValue.setDataType(STRING_DATATYPE);
297 String actionDictType = getActionPolicyDict(comboDictValue).getType();
298 typeAttributeValue.getContent().add(actionDictType);
300 assignmentType.setExpression(new ObjectFactory().createAttributeValue(typeAttributeValue));
301 obligation.getAttributeAssignmentExpression().add(assignmentType);
303 // Add Rest_URL Assignment:
304 AttributeAssignmentExpressionType assignmentURL = new AttributeAssignmentExpressionType();
305 assignmentURL.setAttributeId(URL_ATTRIBUTEID);
306 assignmentURL.setCategory(CATEGORY_RESOURCE);
308 AttributeValueType actionURLAttributeValue = new AttributeValueType();
309 actionURLAttributeValue.setDataType(URI_DATATYPE);
310 String actionDictUrl = getActionPolicyDict(comboDictValue).getUrl();
311 actionURLAttributeValue.getContent().add(actionDictUrl);
313 assignmentURL.setExpression(new ObjectFactory().createAttributeValue(actionURLAttributeValue));
314 obligation.getAttributeAssignmentExpression().add(assignmentURL);
316 // Add Method Assignment:
317 AttributeAssignmentExpressionType assignmentMethod = new AttributeAssignmentExpressionType();
318 assignmentMethod.setAttributeId(METHOD_ATTRIBUTEID);
319 assignmentMethod.setCategory(CATEGORY_RESOURCE);
321 AttributeValueType methodAttributeValue = new AttributeValueType();
322 methodAttributeValue.setDataType(STRING_DATATYPE);
323 String actionDictMethod = getActionPolicyDict(comboDictValue).getMethod();
324 methodAttributeValue.getContent().add(actionDictMethod);
326 assignmentMethod.setExpression(new ObjectFactory().createAttributeValue(methodAttributeValue));
327 obligation.getAttributeAssignmentExpression().add(assignmentMethod);
329 // Add JSON_URL Assignment:
330 String actionBody = getActionPolicyDict(comboDictValue).getBody();
331 if (actionBody != null) {
332 AttributeAssignmentExpressionType assignmentJsonURL = new AttributeAssignmentExpressionType();
333 assignmentJsonURL.setAttributeId(BODY_ATTRIBUTEID);
334 assignmentJsonURL.setCategory(CATEGORY_RESOURCE);
336 AttributeValueType jsonURLAttributeValue = new AttributeValueType();
337 jsonURLAttributeValue.setDataType(URI_DATATYPE);
338 jsonURLAttributeValue.getContent().add(CONFIG_URL + "/Action/" + policyName + ".json");
340 assignmentJsonURL.setExpression(new ObjectFactory().createAttributeValue(jsonURLAttributeValue));
341 obligation.getAttributeAssignmentExpression().add(assignmentJsonURL);
344 if(getActionPolicyDict(comboDictValue).getHeader() != null){
345 String headerVal = getActionPolicyDict(comboDictValue).getHeader();
346 if(headerVal != null && !headerVal.equals("")){
347 // parse it on : to get number of headers
348 String[] result = headerVal.split(":");
349 for (String eachString : result){
350 // parse each value on =
351 String[] textFieldVals = eachString.split("=");
352 obligation.getAttributeAssignmentExpression().add(addDynamicHeaders(textFieldVals[0], textFieldVals[1]));
358 obligations.getObligationExpression().add(obligation);
363 // if compound setting the inner apply here
364 protected ApplyType getInnerActionApply(String value1Label) {
365 ApplyType actionApply = new ApplyType();
367 // check the index for the label.
368 for (String labelAttr : dynamicLabelRuleAlgorithms) {
369 if (labelAttr.equals(value1Label)) {
370 String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString();
371 // check if the row contains label again
372 for (String labelValue : dynamicLabelRuleAlgorithms) {
373 if (labelValue.equals(value1)) {
374 return getCompoundApply(index);
378 // Getting the values from the form.
379 String functionKey = dynamicFieldFunctionRuleAlgorithms.get(index).toString();
380 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
381 actionApply.setFunctionId(dropDownMap.get(functionKey));
382 // if two text field are rule attributes.
383 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
384 ApplyType innerActionApply1 = new ApplyType();
385 ApplyType innerActionApply2 = new ApplyType();
386 AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
387 AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
388 // If selected function is Integer function set integer functionID
389 if (functionKey.toLowerCase().contains("integer")) {
390 innerActionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
391 innerActionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
392 attributeDesignator1.setDataType(INTEGER_DATATYPE);
393 attributeDesignator2.setDataType(INTEGER_DATATYPE);
395 // If selected function is not a Integer function
396 // set String functionID
397 innerActionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
398 innerActionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
399 attributeDesignator1.setDataType(STRING_DATATYPE);
400 attributeDesignator2.setDataType(STRING_DATATYPE);
402 attributeDesignator1.setCategory(CATEGORY_RESOURCE);
403 attributeDesignator2.setCategory(CATEGORY_RESOURCE);
405 // Here set actual field values
406 attributeDesignator1.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8));
407 attributeDesignator2.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8));
409 innerActionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator1));
410 innerActionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator2));
412 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply1));
413 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply2));
415 } else {// if either of one text field is rule attribute.
416 ApplyType innerActionApply = new ApplyType();
417 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
418 AttributeValueType actionConditionAttributeValue = new AttributeValueType();
420 if (functionKey.toLowerCase().contains("integer")) {
421 innerActionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
422 actionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
423 attributeDesignator.setDataType(INTEGER_DATATYPE);
425 innerActionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
426 actionConditionAttributeValue.setDataType(STRING_DATATYPE);
427 attributeDesignator.setDataType(STRING_DATATYPE);
430 String attributeId = null;
431 String attributeValue = null;
433 // Find which textField has rule attribute and set it as
434 attributeId = value1;
435 attributeValue = value2;
437 if (attributeId != null) {
438 attributeDesignator.setCategory(CATEGORY_RESOURCE);
439 attributeDesignator.setAttributeId(attributeId);
441 actionConditionAttributeValue.getContent().add(attributeValue);
442 innerActionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
443 // Decide the order of element based the values.
444 if (attributeId.equals(value1)) {
445 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
446 actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
448 actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
449 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
458 // if the rule algorithm is multiple compound one setting the apply
459 protected ApplyType getCompoundApply(int index) {
460 ApplyType actionApply = new ApplyType();
461 String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index).toString();
462 String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString();
463 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
464 actionApply.setFunctionId(dropDownMap.get(selectedFunction));
465 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
466 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
470 // Adding the dynamic headers if any
471 private AttributeAssignmentExpressionType addDynamicHeaders(String header, String value) {
472 AttributeAssignmentExpressionType assignmentHeaders = new AttributeAssignmentExpressionType();
473 assignmentHeaders.setAttributeId("headers:" + header);
474 assignmentHeaders.setCategory(CATEGORY_RESOURCE);
476 AttributeValueType headersAttributeValue = new AttributeValueType();
477 headersAttributeValue.setDataType(STRING_DATATYPE);
478 headersAttributeValue.getContent().add(value);
480 assignmentHeaders.setExpression(new ObjectFactory().createAttributeValue(headersAttributeValue));
481 return assignmentHeaders;
484 private Map<String,String> createDropDownMap(){
485 JPAUtils jpaUtils = null;
486 Map<String, String> dropDownMap = new HashMap<>();
488 jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
489 } catch (Exception e) {
490 LOGGER.error("Exception Occured"+e);
492 if(jpaUtils != null){
493 Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
495 for (Datatype id : functionMap.keySet()) {
496 List<FunctionDefinition> functionDefinitions = (List<FunctionDefinition>) functionMap
498 for (FunctionDefinition functionDef : functionDefinitions) {
499 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
506 private ActionPolicyDict getActionPolicyDict(String attributeName){
507 ActionPolicyDict retObj = new ActionPolicyDict();
508 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
509 Query getActionPolicyDicts = em.createNamedQuery("ActionPolicyDict.findAll");
510 List<?> actionPolicyDicts = getActionPolicyDicts.getResultList();
512 for (Object id : actionPolicyDicts) {
513 ActionPolicyDict actionPolicy = (ActionPolicyDict) id;
514 if(attributeName.equals(actionPolicy.getAttributeName())){
516 retObj = actionPolicy;
525 public Object getCorrectPolicyDataObject() {
526 return policyAdapter.getPolicyData();