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.onap.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 oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
35 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
50 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
51 import org.onap.policy.pap.xacml.rest.util.JPAUtils;
52 import org.onap.policy.rest.adapter.PolicyRestAdapter;
53 import org.onap.policy.rest.jpa.Datatype;
54 import org.onap.policy.rest.jpa.FunctionDefinition;
55 import org.onap.policy.xacml.api.XACMLErrorConstants;
57 import com.att.research.xacml.api.pap.PAPException;
59 import org.onap.policy.common.logging.eelf.MessageCodes;
60 import org.onap.policy.common.logging.eelf.PolicyLogger;
61 import org.onap.policy.common.logging.flexlogger.FlexLogger;
62 import org.onap.policy.common.logging.flexlogger.Logger;
64 public class ActionPolicy extends Policy {
69 private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicy.class);
71 public static final String JSON_CONFIG = "JSON";
73 public static final String PDP_ACTION = "PDP";
74 public static final String PEP_ACTION = "PEP";
75 public static final String TYPE_ACTION = "REST";
77 public static final String GET_METHOD = "GET";
78 public static final String PUT_METHOD = "PUT";
79 public static final String POST_METHOD = "POST";
81 public static final String PERFORMER_ATTRIBUTEID = "performer";
82 public static final String TYPE_ATTRIBUTEID = "type";
83 public static final String METHOD_ATTRIBUTEID = "method";
84 public static final String HEADERS_ATTRIBUTEID = "headers";
85 public static final String URL_ATTRIBUTEID = "url";
86 public static final String BODY_ATTRIBUTEID = "body";
88 List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
89 List<String> dynamicFieldFunctionRuleAlgorithms = new LinkedList<>();
90 List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
91 List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
93 protected Map<String, String> dropDownMap = new HashMap<>();
95 private static boolean isAttribute = false;
96 private synchronized static boolean getAttribute () {
101 public ActionPolicy() {
105 public ActionPolicy(PolicyRestAdapter policyAdapter){
106 this.policyAdapter = policyAdapter;
110 public Map<String, String> savePolicies() throws PAPException {
112 Map<String, String> successMap = new HashMap<>();
113 if(isPolicyExists()){
114 successMap.put("EXISTS", "This Policy already exist on the PAP");
118 if(!ActionPolicy.getAttribute()) {
119 successMap.put("invalidAttribute", "Action Attrbute was not in the database.");
123 if(!isPreparedToSave()){
124 //Prep and configure the policy for saving
128 // Until here we prepared the data and here calling the method to create xml.
129 Path newPolicyPath = null;
130 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
131 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() );
135 //This is the method for preparing the policy for saving. We have broken it out
136 //separately because the fully configured policy is used for multiple things
138 public boolean prepareToSave() throws PAPException{
140 if(isPreparedToSave()){
141 //we have already done this
146 String policyID = policyAdapter.getPolicyID();
147 version = policyAdapter.getHighestVersion();
149 // Create the Instance for pojo, PolicyType object is used in marshalling.
150 if (policyAdapter.getPolicyType().equals("Action")) {
151 PolicyType policyConfig = new PolicyType();
153 policyConfig.setVersion(Integer.toString(version));
154 policyConfig.setPolicyId(policyID);
155 policyConfig.setTarget(new TargetType());
156 policyAdapter.setData(policyConfig);
159 policyName = policyAdapter.getNewFileName();
161 if (policyAdapter.getData() != null) {
162 // Action body is optional so checking value provided or not
163 String comboDictValue = policyAdapter.getActionAttribute();
164 String actionBody = policyAdapter.getActionBody();
167 //if actionBody is null or empty then we know the ActionAttribute in the request does not exist in the dictionary
168 if(!(actionBody==null || "".equals(actionBody))){
169 saveActionBody(policyName, actionBody);
173 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not find " + comboDictValue + " in the ActionPolicyDict table.");
178 PolicyType actionPolicy = (PolicyType) policyAdapter.getData();
179 actionPolicy.setDescription(policyAdapter.getPolicyDescription());
180 actionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
182 AllOfType allOf = new AllOfType();
184 Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
186 // If there is any dynamic field attributes create the matches here
187 for (String keyField : dynamicFieldComponentAttributes.keySet()) {
188 String key = keyField;
189 String value = dynamicFieldComponentAttributes.get(key);
190 MatchType dynamicMatch = createDynamicMatch(key, value);
191 allOf.getMatch().add(dynamicMatch);
194 AnyOfType anyOf = new AnyOfType();
195 anyOf.getAllOf().add(allOf);
197 TargetType target = new TargetType();
198 target.getAnyOf().add(anyOf);
200 // Adding the target to the policy element
201 actionPolicy.setTarget(target);
203 RuleType rule = new RuleType();
204 rule.setRuleId(policyAdapter.getRuleID());
206 rule.setEffect(EffectType.PERMIT);
207 rule.setTarget(new TargetType());
209 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
210 dynamicFieldFunctionRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
211 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
212 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
213 //dropDownMap = policyAdapter.getDropDownMap();
214 dropDownMap = createDropDownMap();
216 // Rule attributes are optional and dynamic so check and add them to condition.
217 if (dynamicLabelRuleAlgorithms != null && dynamicLabelRuleAlgorithms.size() > 0) {
218 boolean isCompound = false;
219 ConditionType condition = new ConditionType();
220 int index = dynamicFieldOneRuleAlgorithms.size() - 1;
222 for (String labelAttr : dynamicLabelRuleAlgorithms) {
223 // if the rule algorithm as a label means it is a compound
224 if (dynamicFieldOneRuleAlgorithms.get(index).toString().equals(labelAttr)) {
225 ApplyType actionApply = new ApplyType();
227 String selectedFunction = (String) dynamicFieldFunctionRuleAlgorithms.get(index).toString();
228 String value1 = (String) dynamicFieldOneRuleAlgorithms.get(index).toString();
229 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
230 actionApply.setFunctionId(dropDownMap.get(selectedFunction));
231 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
232 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
233 condition.setExpression(new ObjectFactory().createApply(actionApply));
237 // if rule algorithm not a compound
239 condition.setExpression(new ObjectFactory().createApply(getInnerActionApply(dynamicLabelRuleAlgorithms.get(index).toString())));
241 rule.setCondition(condition);
243 // set the obligations to rule
244 rule.setObligationExpressions(getObligationExpressions());
245 actionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
246 policyAdapter.setPolicyData(actionPolicy);
248 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
251 setPreparedToSave(true);
255 // Saving the json Configurations file if exists at server location for action policy.
256 private void saveActionBody(String policyName, String actionBodyData) {
258 if(policyName.endsWith(".xml")){
259 policyName = policyName.replace(".xml", "");
261 File file = new File(ACTION_HOME+ File.separator + policyName + ".json");
262 FileWriter fw = new FileWriter(file.getAbsoluteFile());
263 BufferedWriter bw = new BufferedWriter(fw);
264 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.equals("")){
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().add(addDynamicHeaders(textFieldVals[0], textFieldVals[1]));
360 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).toString();
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).toString();
382 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
383 actionApply.setFunctionId(dropDownMap.get(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
408 attributeDesignator1.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8));
409 attributeDesignator2.setAttributeId(value1.contains("resource:") ? value1.substring(9): value1.substring(8));
411 innerActionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator1));
412 innerActionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator2));
414 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply1));
415 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply2));
417 } else {// if either of one text field is rule attribute.
418 ApplyType innerActionApply = new ApplyType();
419 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
420 AttributeValueType actionConditionAttributeValue = new AttributeValueType();
422 if (functionKey.toLowerCase().contains("integer")) {
423 innerActionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
424 actionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
425 attributeDesignator.setDataType(INTEGER_DATATYPE);
427 innerActionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
428 actionConditionAttributeValue.setDataType(STRING_DATATYPE);
429 attributeDesignator.setDataType(STRING_DATATYPE);
432 String attributeId = null;
433 String attributeValue = null;
435 // Find which textField has rule attribute and set it as
436 attributeId = value1;
437 attributeValue = value2;
439 if (attributeId != null) {
440 attributeDesignator.setCategory(CATEGORY_RESOURCE);
441 attributeDesignator.setAttributeId(attributeId);
443 actionConditionAttributeValue.getContent().add(attributeValue);
444 innerActionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
445 // Decide the order of element based the values.
446 if (attributeId.equals(value1)) {
447 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
448 actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
450 actionApply.getExpression().add(new ObjectFactory().createAttributeValue(actionConditionAttributeValue));
451 actionApply.getExpression().add(new ObjectFactory().createApply(innerActionApply));
460 // if the rule algorithm is multiple compound one setting the apply
461 protected ApplyType getCompoundApply(int index) {
462 ApplyType actionApply = new ApplyType();
463 String selectedFunction = dynamicFieldFunctionRuleAlgorithms.get(index).toString();
464 String value1 = dynamicFieldOneRuleAlgorithms.get(index).toString();
465 String value2 = dynamicFieldTwoRuleAlgorithms.get(index).toString();
466 actionApply.setFunctionId(dropDownMap.get(selectedFunction));
467 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value1)));
468 actionApply.getExpression().add(new ObjectFactory().createApply(getInnerActionApply(value2)));
472 // Adding the dynamic headers if any
473 private AttributeAssignmentExpressionType addDynamicHeaders(String header, String value) {
474 AttributeAssignmentExpressionType assignmentHeaders = new AttributeAssignmentExpressionType();
475 assignmentHeaders.setAttributeId("headers:" + header);
476 assignmentHeaders.setCategory(CATEGORY_RESOURCE);
478 AttributeValueType headersAttributeValue = new AttributeValueType();
479 headersAttributeValue.setDataType(STRING_DATATYPE);
480 headersAttributeValue.getContent().add(value);
482 assignmentHeaders.setExpression(new ObjectFactory().createAttributeValue(headersAttributeValue));
483 return assignmentHeaders;
486 private Map<String,String> createDropDownMap(){
487 JPAUtils jpaUtils = null;
488 Map<String, String> dropDownMap = new HashMap<>();
490 jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
491 } catch (Exception e) {
492 LOGGER.error("Exception Occured"+e);
494 if(jpaUtils != null){
495 Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
497 for (Datatype id : functionMap.keySet()) {
498 List<FunctionDefinition> functionDefinitions = (List<FunctionDefinition>) functionMap
500 for (FunctionDefinition functionDef : functionDefinitions) {
501 dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid());
509 public Object getCorrectPolicyDataObject() {
510 return policyAdapter.getPolicyData();