2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2019 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.onap.policy.pap.xacml.rest.components;
23 import com.att.research.xacml.api.pap.PAPException;
25 import java.io.BufferedWriter;
27 import java.io.FileWriter;
28 import java.io.IOException;
29 import java.nio.file.Path;
30 import java.nio.file.Paths;
31 import java.util.HashMap;
32 import java.util.LinkedList;
33 import java.util.List;
35 import java.util.Objects;
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.onap.policy.common.logging.eelf.MessageCodes;
54 import org.onap.policy.common.logging.eelf.PolicyLogger;
55 import org.onap.policy.common.logging.flexlogger.FlexLogger;
56 import org.onap.policy.common.logging.flexlogger.Logger;
57 import org.onap.policy.rest.adapter.PolicyRestAdapter;
58 import org.onap.policy.rest.dao.CommonClassDao;
59 import org.onap.policy.rest.jpa.FunctionDefinition;
60 import org.onap.policy.xacml.api.XACMLErrorConstants;
62 public class ActionPolicy extends Policy {
64 private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicy.class);
66 public static final String JSON_CONFIG = "JSON";
68 public static final String PDP_ACTION = "PDP";
69 public static final String PEP_ACTION = "PEP";
70 public static final String TYPE_ACTION = "REST";
72 public static final String GET_METHOD = "GET";
73 public static final String PUT_METHOD = "PUT";
74 public static final String POST_METHOD = "POST";
76 public static final String PERFORMER_ATTRIBUTEID = "performer";
77 public static final String TYPE_ATTRIBUTEID = "type";
78 public static final String METHOD_ATTRIBUTEID = "method";
79 public static final String HEADERS_ATTRIBUTEID = "headers";
80 public static final String URL_ATTRIBUTEID = "url";
81 public static final String BODY_ATTRIBUTEID = "body";
83 List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
84 List<String> dynamicFieldFunctionRuleAlgorithms = new LinkedList<>();
85 List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
86 List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
88 private CommonClassDao commonClassDao;
90 private static boolean isAttribute = false;
92 private static synchronized boolean getAttribute() {
97 public ActionPolicy() {
101 public ActionPolicy(PolicyRestAdapter policyAdapter, CommonClassDao commonClassDao) {
102 this.policyAdapter = policyAdapter;
103 this.commonClassDao = commonClassDao;
107 public Map<String, String> savePolicies() throws PAPException {
109 Map<String, String> successMap = new HashMap<>();
110 if (isPolicyExists()) {
111 successMap.put("EXISTS", "This Policy already exist on the PAP");
115 if (!ActionPolicy.getAttribute()) {
116 successMap.put("invalidAttribute", "Action Attrbute was not in the database.");
120 if (!isPreparedToSave()) {
121 // Prep and configure the policy for saving
125 // Until here we prepared the data and here calling the method to create xml.
126 Path newPolicyPath = null;
127 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
128 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
132 // This is the method for preparing the policy for saving. We have broken it out
133 // separately because the fully configured policy is used for multiple things
135 public boolean prepareToSave() throws PAPException {
137 if (isPreparedToSave()) {
138 // we have already done this
143 String policyID = policyAdapter.getPolicyID();
144 version = policyAdapter.getHighestVersion();
146 // Create the Instance for pojo, PolicyType object is used in marshalling.
147 if (policyAdapter.getPolicyType().equals("Action")) {
148 PolicyType policyConfig = new PolicyType();
150 policyConfig.setVersion(Integer.toString(version));
151 policyConfig.setPolicyId(policyID);
152 policyConfig.setTarget(new TargetType());
153 policyAdapter.setData(policyConfig);
156 policyName = policyAdapter.getNewFileName();
158 if (policyAdapter.getData() != null) {
159 // Action body is optional so checking value provided or not
160 String comboDictValue = policyAdapter.getActionAttribute();
161 String actionBody = policyAdapter.getActionBody();
164 // if actionBody is null or empty then we know the ActionAttribute in the request does not exist in the
166 if (!(actionBody == null || "".equals(actionBody))) {
167 saveActionBody(policyName, actionBody);
170 if (!getAttribute()) {
171 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + comboDictValue
172 + " in the ActionPolicyDict table.");
177 PolicyType actionPolicy = (PolicyType) policyAdapter.getData();
178 actionPolicy.setDescription(policyAdapter.getPolicyDescription());
179 actionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
181 AllOfType allOf = new AllOfType();
183 Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
185 // If there is any dynamic field attributes create the matches here
186 for (String keyField : dynamicFieldComponentAttributes.keySet()) {
187 String key = keyField;
188 String value = dynamicFieldComponentAttributes.get(key);
189 MatchType dynamicMatch = createDynamicMatch(key, value);
190 allOf.getMatch().add(dynamicMatch);
193 AnyOfType anyOf = new AnyOfType();
194 anyOf.getAllOf().add(allOf);
196 TargetType target = new TargetType();
197 target.getAnyOf().add(anyOf);
199 // Adding the target to the policy element
200 actionPolicy.setTarget(target);
202 RuleType rule = new RuleType();
203 rule.setRuleId(policyAdapter.getRuleID());
205 rule.setEffect(EffectType.PERMIT);
206 rule.setTarget(new TargetType());
208 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
209 dynamicFieldFunctionRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
210 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
211 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
213 // Rule attributes are optional and dynamic so check and add them to condition.
214 if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
215 boolean isCompound = false;
216 ConditionType condition = new ConditionType();
217 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
219 for (String labelAttr : dynamicLabelRuleAlgorithms) {
220 // if the rule algorithm as a label means it is a compound
221 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
222 ApplyType actionApply = new ApplyType();
224 String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index);
225 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
226 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
227 actionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
228 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
229 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
230 condition.setExpression(new ObjectFactory().createApply(actionApply));
234 // if rule algorithm not a compound
236 condition.setExpression(new ObjectFactory()
237 .createApply(getInnerActionApply(dynamicLabelRuleAlgorithms.get(index))));
239 rule.setCondition(condition);
241 // set the obligations to rule
242 rule.setObligationExpressions(getObligationExpressions());
243 actionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
244 policyAdapter.setPolicyData(actionPolicy);
246 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."
247 + Objects.requireNonNull(policyAdapter.getData()).getClass().getCanonicalName());
250 setPreparedToSave(true);
254 private static synchronized void setAttribute(boolean b) {
258 // Saving the json Configurations file if exists at server location for action policy.
259 private void saveActionBody(String policyName, String actionBodyData) {
260 if (policyName.endsWith(".xml")) {
261 policyName = policyName.replace(".xml", "");
263 File file = new File(ACTION_HOME + File.separator + policyName + ".json");
264 try (BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()))) {
265 bw.write(actionBodyData);
266 if (LOGGER.isInfoEnabled()) {
267 LOGGER.info("Action Body is succesfully saved at " + file.getAbsolutePath());
269 } catch (IOException e) {
270 LOGGER.error("Exception Occured" + e);
274 // Data required for obligation part is setting here.
275 private ObligationExpressionsType getObligationExpressions() {
276 ObligationExpressionsType obligations = new ObligationExpressionsType();
278 ObligationExpressionType obligation = new ObligationExpressionType();
279 String comboDictValue = policyAdapter.getActionAttribute();
280 obligation.setObligationId(comboDictValue);
281 obligation.setFulfillOn(EffectType.PERMIT);
283 // Add Action Assignment:
284 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
285 assignment1.setAttributeId(PERFORMER_ATTRIBUTEID);
286 assignment1.setCategory(CATEGORY_RECIPIENT_SUBJECT);
288 AttributeValueType actionNameAttributeValue = new AttributeValueType();
289 actionNameAttributeValue.setDataType(STRING_DATATYPE);
290 actionNameAttributeValue.getContent().add(performer.get(policyAdapter.getActionPerformer()));
292 assignment1.setExpression(new ObjectFactory().createAttributeValue(actionNameAttributeValue));
293 obligation.getAttributeAssignmentExpression().add(assignment1);
295 // Add Type Assignment:
296 AttributeAssignmentExpressionType assignmentType = new AttributeAssignmentExpressionType();
297 assignmentType.setAttributeId(TYPE_ATTRIBUTEID);
298 assignmentType.setCategory(CATEGORY_RESOURCE);
300 AttributeValueType typeAttributeValue = new AttributeValueType();
301 typeAttributeValue.setDataType(STRING_DATATYPE);
302 String actionDictType = policyAdapter.getActionDictType();
303 typeAttributeValue.getContent().add(actionDictType);
305 assignmentType.setExpression(new ObjectFactory().createAttributeValue(typeAttributeValue));
306 obligation.getAttributeAssignmentExpression().add(assignmentType);
308 // Add Rest_URL Assignment:
309 AttributeAssignmentExpressionType assignmentURL = new AttributeAssignmentExpressionType();
310 assignmentURL.setAttributeId(URL_ATTRIBUTEID);
311 assignmentURL.setCategory(CATEGORY_RESOURCE);
313 AttributeValueType actionURLAttributeValue = new AttributeValueType();
314 actionURLAttributeValue.setDataType(URI_DATATYPE);
315 String actionDictUrl = policyAdapter.getActionDictUrl();
316 actionURLAttributeValue.getContent().add(actionDictUrl);
318 assignmentURL.setExpression(new ObjectFactory().createAttributeValue(actionURLAttributeValue));
319 obligation.getAttributeAssignmentExpression().add(assignmentURL);
321 // Add Method Assignment:
322 AttributeAssignmentExpressionType assignmentMethod = new AttributeAssignmentExpressionType();
323 assignmentMethod.setAttributeId(METHOD_ATTRIBUTEID);
324 assignmentMethod.setCategory(CATEGORY_RESOURCE);
326 AttributeValueType methodAttributeValue = new AttributeValueType();
327 methodAttributeValue.setDataType(STRING_DATATYPE);
328 String actionDictMethod = policyAdapter.getActionDictMethod();
329 methodAttributeValue.getContent().add(actionDictMethod);
331 assignmentMethod.setExpression(new ObjectFactory().createAttributeValue(methodAttributeValue));
332 obligation.getAttributeAssignmentExpression().add(assignmentMethod);
334 // Add JSON_URL Assignment:
335 String actionBody = policyAdapter.getActionBody();
336 if (actionBody != null) {
337 AttributeAssignmentExpressionType assignmentJsonURL = new AttributeAssignmentExpressionType();
338 assignmentJsonURL.setAttributeId(BODY_ATTRIBUTEID);
339 assignmentJsonURL.setCategory(CATEGORY_RESOURCE);
341 AttributeValueType jsonURLAttributeValue = new AttributeValueType();
342 jsonURLAttributeValue.setDataType(URI_DATATYPE);
343 jsonURLAttributeValue.getContent().add(CONFIG_URL + "/Action/" + policyName + ".json");
345 assignmentJsonURL.setExpression(new ObjectFactory().createAttributeValue(jsonURLAttributeValue));
346 obligation.getAttributeAssignmentExpression().add(assignmentJsonURL);
349 String headerVal = policyAdapter.getActionDictHeader();
350 if (headerVal != null && !headerVal.trim().isEmpty()) {
351 // parse it on : to get number of headers
352 String[] result = headerVal.split(":");
353 for (String eachString : result) {
354 // parse each value on =
355 String[] textFieldVals = eachString.split("=");
356 obligation.getAttributeAssignmentExpression()
357 .add(addDynamicHeaders(textFieldVals[0], textFieldVals[1]));
361 obligations.getObligationExpression().add(obligation);
365 // if compound setting the inner apply here
366 protected ApplyType getInnerActionApply(String value1Label) {
367 ApplyType actionApply = new ApplyType();
369 // check the index for the label.
370 for (String labelAttr : dynamicLabelRuleAlgorithms) {
371 if (labelAttr.equals(value1Label)) {
372 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
373 // check if the row contains label again
374 for (String labelValue : dynamicLabelRuleAlgorithms) {
375 if (labelValue.equals(value1)) {
376 return getCompoundApply(index);
380 // Getting the values from the form.
381 String functionKey = dynamicFieldFunctionRuleAlgorithms.get(index);
382 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
383 actionApply.setFunctionId(getFunctionDefinitionId(functionKey));
384 // if two text field are rule attributes.
385 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
386 ApplyType innerActionApply1 = new ApplyType();
387 ApplyType innerActionApply2 = new ApplyType();
388 AttributeDesignatorType attributeDesignator1 = new AttributeDesignatorType();
389 AttributeDesignatorType attributeDesignator2 = new AttributeDesignatorType();
390 // If selected function is Integer function set integer functionID
391 if (functionKey.toLowerCase().contains("integer")) {
392 innerActionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
393 innerActionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
394 attributeDesignator1.setDataType(INTEGER_DATATYPE);
395 attributeDesignator2.setDataType(INTEGER_DATATYPE);
397 // If selected function is not a Integer function
398 // set String functionID
399 innerActionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
400 innerActionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
401 attributeDesignator1.setDataType(STRING_DATATYPE);
402 attributeDesignator2.setDataType(STRING_DATATYPE);
404 attributeDesignator1.setCategory(CATEGORY_RESOURCE);
405 attributeDesignator2.setCategory(CATEGORY_RESOURCE);
407 // Here set actual field values
409 .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
411 .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8));
413 innerActionApply1.getExpression()
414 .add(new ObjectFactory().createAttributeDesignator(attributeDesignator1));
415 innerActionApply2.getExpression()
416 .add(new ObjectFactory().createAttributeDesignator(attributeDesignator2));
418 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply1));
419 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply2));
421 } else {// if either of one text field is rule attribute.
422 ApplyType innerActionApply = new ApplyType();
423 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
424 AttributeValueType actionConditionAttributeValue = new AttributeValueType();
426 if (functionKey.toLowerCase().contains("integer")) {
427 innerActionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
428 actionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
429 attributeDesignator.setDataType(INTEGER_DATATYPE);
431 innerActionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
432 actionConditionAttributeValue.setDataType(STRING_DATATYPE);
433 attributeDesignator.setDataType(STRING_DATATYPE);
436 String attributeId = null;
437 String attributeValue = null;
439 // Find which textField has rule attribute and set it as
440 attributeId = value1;
441 attributeValue = value2;
443 if (attributeId != null) {
444 attributeDesignator.setCategory(CATEGORY_RESOURCE);
445 attributeDesignator.setAttributeId(attributeId);
447 actionConditionAttributeValue.getContent().add(attributeValue);
448 innerActionApply.getExpression()
449 .add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
450 // Decide the order of element based the values.
451 if (attributeId.equals(value1)) {
452 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
453 actionApply.getExpression()
454 .add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
456 actionApply.getExpression()
457 .add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
458 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
467 // if the rule algorithm is multiple compound one setting the apply
468 protected ApplyType getCompoundApply(int index) {
469 ApplyType actionApply = new ApplyType();
470 String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index);
471 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
472 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
473 actionApply.setFunctionId(getFunctionDefinitionId(selectedFunction));
474 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
475 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
479 // Adding the dynamic headers if any
480 private AttributeAssignmentExpressionType addDynamicHeaders(String header, String value) {
481 AttributeAssignmentExpressionType assignmentHeaders = new AttributeAssignmentExpressionType();
482 assignmentHeaders.setAttributeId("headers:" + header);
483 assignmentHeaders.setCategory(CATEGORY_RESOURCE);
485 AttributeValueType headersAttributeValue = new AttributeValueType();
486 headersAttributeValue.setDataType(STRING_DATATYPE);
487 headersAttributeValue.getContent().add(value);
489 assignmentHeaders.setExpression(new ObjectFactory().createAttributeValue(headersAttributeValue));
490 return assignmentHeaders;
494 public Object getCorrectPolicyDataObject() {
495 return policyAdapter.getPolicyData();
498 public String getFunctionDefinitionId(String key) {
499 FunctionDefinition object =
500 (FunctionDefinition) commonClassDao.getEntityItem(FunctionDefinition.class, "short_name", key);
501 if (object != null) {
502 return object.getXacmlid();