[POLICY-73] replace openecomp for policy-engine
[policy/engine.git] / ONAP-PAP-REST / src / main / java / org / onap / policy / pap / xacml / rest / components / DecisionPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP-PAP-REST
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.policy.pap.xacml.rest.components;
22
23 import java.io.ByteArrayInputStream;
24 import java.io.File;
25 import java.io.IOException;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.nio.charset.StandardCharsets;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.HashMap;
35 import java.util.LinkedList;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.UUID;
39
40 import javax.persistence.EntityManager;
41 import javax.persistence.Query;
42
43 import org.onap.policy.common.logging.eelf.MessageCodes;
44 import org.onap.policy.common.logging.eelf.PolicyLogger;
45 import org.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.controlloop.policy.builder.BuilderException;
48 import org.onap.policy.controlloop.policy.builder.Results;
49 import org.onap.policy.controlloop.policy.guard.Constraint;
50 import org.onap.policy.controlloop.policy.guard.ControlLoopGuard;
51 import org.onap.policy.controlloop.policy.guard.Guard;
52 import org.onap.policy.controlloop.policy.guard.GuardPolicy;
53 import org.onap.policy.controlloop.policy.guard.MatchParameters;
54 import org.onap.policy.controlloop.policy.guard.builder.ControlLoopGuardBuilder;
55 import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
56 import org.onap.policy.pap.xacml.rest.util.JPAUtils;
57 import org.onap.policy.rest.adapter.PolicyRestAdapter;
58 import org.onap.policy.rest.jpa.Datatype;
59 import org.onap.policy.rest.jpa.DecisionSettings;
60 import org.onap.policy.rest.jpa.FunctionDefinition;
61 import org.onap.policy.utils.PolicyUtils;
62 import org.onap.policy.xacml.api.XACMLErrorConstants;
63 import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine;
64 import org.onap.policy.xacml.util.XACMLPolicyScanner;
65
66 import com.att.research.xacml.std.IdentifierImpl;
67
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType;
73 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
74 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
75 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType;
84 import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType;
85
86 public class DecisionPolicy extends Policy {
87         
88         private static final Logger LOGGER      = FlexLogger.getLogger(DecisionPolicy.class);
89         
90         public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not";
91         private static final String AAFPROVIDER = "AAF";
92         public static final String GUARD_YAML = "GUARD_YAML";
93     public static final String GUARD_BL_YAML = "GUARD_BL_YAML";
94     public static final String RAINY_DAY = "Rainy_Day";
95     private static final String XACML_GUARD_TEMPLATE = "Decision_GuardPolicyTemplate.xml";
96     private static final String XACML_BLGUARD_TEMPLATE = "Decision_GuardBLPolicyTemplate.xml";
97
98         private static final String ONAPNAME = "ONAPName";
99         private static final String POLICY_NAME = "PolicyName";
100         private static final String DESCRIPTION = "description";
101
102         
103         List<String> dynamicLabelRuleAlgorithms = new LinkedList<>();
104         List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>();
105         List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
106         List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
107         List<String> dataTypeList = new LinkedList<>();
108         
109         protected Map<String, String> dropDownMap = new HashMap<>();
110         
111
112         public DecisionPolicy() {
113                 super();
114         }
115         
116         public DecisionPolicy(PolicyRestAdapter policyAdapter){
117                 this.policyAdapter = policyAdapter;
118         }
119         
120         @Override
121         public Map<String, String> savePolicies() throws Exception {
122
123                 Map<String, String> successMap = new HashMap<>();
124                 if(isPolicyExists()){
125                         successMap.put("EXISTS", "This Policy already exist on the PAP");
126                         return successMap;
127                 }
128
129                 if(!isPreparedToSave()){
130                         //Prep and configure the policy for saving
131                         prepareToSave();
132                 }
133
134                 // Until here we prepared the data and here calling the method to create xml.
135                 Path newPolicyPath = null;
136                 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
137
138                 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());  
139                 return successMap;              
140         }
141         
142         //This is the method for preparing the policy for saving.  We have broken it out
143         //separately because the fully configured policy is used for multiple things
144         @Override
145         public boolean prepareToSave() throws Exception{
146
147                 if(isPreparedToSave()){
148                         //we have already done this
149                         return true;
150                 }
151                 
152                 int version = 0;
153                 String policyID = policyAdapter.getPolicyID();
154                 version = policyAdapter.getHighestVersion();
155                 
156                 // Create the Instance for pojo, PolicyType object is used in marshalling.
157                 if ("Decision".equals(policyAdapter.getPolicyType())) {
158                         PolicyType policyConfig = new PolicyType();
159
160                         policyConfig.setVersion(Integer.toString(version));
161                         policyConfig.setPolicyId(policyID);
162                         policyConfig.setTarget(new TargetType());
163                         policyAdapter.setData(policyConfig);
164                 }
165                 policyName = policyAdapter.getNewFileName();
166                 
167                 if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML)){
168                         Map<String, String> yamlParams = new HashMap<>();
169                         yamlParams.put(DESCRIPTION, (policyAdapter.getPolicyDescription()!=null)? policyAdapter.getPolicyDescription(): "YAML Guard Policy");
170                         String fileName = policyAdapter.getNewFileName();
171                         String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
172                         if ((name == null) || ("".equals(name))) {
173                                 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
174                         }
175                         yamlParams.put(POLICY_NAME, name);
176                         yamlParams.put(ONAPNAME, policyAdapter.getOnapName());
177                         Map<String, String> params = policyAdapter.getDynamicFieldConfigAttributes();
178                         yamlParams.putAll(params);
179                         // Call YAML to XACML 
180                         PolicyType decisionPolicy = getGuardPolicy(yamlParams, policyAdapter.getRuleProvider());
181                         decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
182                         decisionPolicy.setVersion(Integer.toString(version));
183                         policyAdapter.setPolicyData(decisionPolicy);
184                         policyAdapter.setData(decisionPolicy);
185                 }else if (policyAdapter.getData() != null) {
186                         PolicyType decisionPolicy = (PolicyType)  policyAdapter.getData();
187                         
188                         decisionPolicy.setDescription(policyAdapter.getPolicyDescription());
189                         
190                         decisionPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
191                         AllOfType allOfOne = new AllOfType();
192                         String fileName = policyAdapter.getNewFileName();
193                         String name = fileName.substring(fileName.lastIndexOf('\\') + 1, fileName.length());
194                         if ((name == null) || ("".equals(name))) {
195                                 name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length());
196                         }
197                         allOfOne.getMatch().add(createMatch(POLICY_NAME, name));
198                         
199                         AllOfType allOf = new AllOfType();
200                         
201                         // Match for Onap
202                         allOf.getMatch().add(createMatch(ONAPNAME, (policyAdapter.getOnapName())));
203                         
204                         Map<String, String> dynamicFieldComponentAttributes = policyAdapter.getDynamicFieldConfigAttributes();
205                         if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
206                                 dynamicFieldComponentAttributes = new HashMap<>();
207                         }
208                         
209                         // If there is any dynamic field attributes create the matches here
210                         for (String keyField : dynamicFieldComponentAttributes.keySet()) {
211                                 String key = keyField;
212                                 String value = dynamicFieldComponentAttributes.get(key);
213                                 MatchType dynamicMatch = createDynamicMatch(key, value);
214                                 allOf.getMatch().add(dynamicMatch);
215                         }
216
217                         AnyOfType anyOf = new AnyOfType();
218                         anyOf.getAllOf().add(allOfOne);
219                         anyOf.getAllOf().add(allOf);
220
221                         TargetType target = new TargetType();
222                         target.getAnyOf().add(anyOf);
223                         decisionPolicy.setTarget(target);
224
225                         Map<String, String> dynamicFieldDecisionSettings = policyAdapter.getDynamicSettingsMap();
226                         if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
227                                 dynamicFieldDecisionSettings = new HashMap<>();
228                         }
229                         
230                         // settings are dynamic so check how many rows are added and add all
231                         for (String keyField : dynamicFieldDecisionSettings.keySet()) {
232                                 String key = keyField;
233                                 String value = dynamicFieldDecisionSettings.get(key);
234                                 String dataType = getDataType(key);
235                                 VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType);
236                                 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable);
237                         }
238                         Map<String, String> dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap();
239                         
240                         if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){
241                                 for(String keyField : dynamicFieldTreatmentAttributes.keySet()) {
242                                         String errorcode = keyField;
243                                         String treatment = dynamicFieldTreatmentAttributes.get(errorcode);
244                                         createRainydayRule(decisionPolicy, errorcode, treatment, true);
245                                 }
246                         } else {
247                                 createRule(decisionPolicy, true);
248                                 createRule(decisionPolicy, false);
249                         }
250
251                 }
252                 setPreparedToSave(true);
253                 return true;
254         }
255         
256         public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) throws BuilderException{
257                 try {
258                         ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
259                         MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe"));
260                         matchParameters.setControlLoopName(yamlParams.get("clname"));
261                         if(yamlParams.containsKey("targets")){
262                                 String targetString = yamlParams.get("targets");
263                                 List<String> targets = null;
264                                 if(targetString!=null && !targetString.isEmpty()){
265                                         if (targetString.contains(",")){
266                                                 targets = Arrays.asList(targetString.split(","));
267                                         }
268                                         else{
269                                                 targets = new ArrayList<>();
270                                                 targets.add(targetString);
271                                         }       
272                                 }
273                                 matchParameters.setTargets(targets);
274                         }
275                         GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters);
276                         builder = builder.addGuardPolicy(policy1);
277             Map<String, String> activeTimeRange = new HashMap<>();
278             activeTimeRange.put("start", yamlParams.get("guardActiveStart"));
279             activeTimeRange.put("end", yamlParams.get("guardActiveEnd"));
280                         String blackListString = yamlParams.get("blackList");
281                         List<String> blackList = null;
282                         if(blackListString!=null){
283                                 if (blackListString.contains(",")){
284                                         blackList = Arrays.asList(blackListString.split(","));                                                          
285                                 }
286                                 else{
287                                         blackList = new ArrayList<>();
288                                         blackList.add(blackListString);
289                                 }       
290                         }
291                         File templateFile;
292                         Path xacmlTemplatePath;
293                         ClassLoader classLoader = getClass().getClassLoader();
294                         Constraint cons = new Constraint();
295                         switch (ruleProvider){
296                         case GUARD_BL_YAML:
297                                 templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
298                                 xacmlTemplatePath = templateFile.toPath();
299                 cons.setActive_time_range(activeTimeRange);
300                 cons.setBlacklist(blackList);
301                                 break;
302                         default:
303                                 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
304                                 xacmlTemplatePath = templateFile.toPath();
305                                 Map<String,String> timeWindow = new HashMap<>();
306                                 if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){
307                                         throw new BuilderException("time window is not in Integer format.");
308                                 }
309                                 String timeUnits = yamlParams.get("timeUnits");
310                                 if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day") 
311                                                 || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){
312                                         throw new BuilderException("time Units is not in proper format.");
313                                 }
314                                 timeWindow.put("value", yamlParams.get("timeWindow"));
315                                 timeWindow.put("units", yamlParams.get("timeUnits"));
316                                 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange);
317                                 break;
318                         }
319                         builder = builder.addLimitConstraint(policy1.getId(), cons);
320                         // Build the specification
321                         Results results = builder.buildSpecification();
322                         // YAML TO XACML 
323                         ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
324                 String xacmlTemplateContent;
325                 try {
326                                 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
327                                 HashMap<String, String> yamlSpecs = new HashMap<>();
328                                 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
329                                 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
330                                 yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME));
331                                 yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor());
332                                 yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe());
333                                 yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName());
334                                 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){
335                                         yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString());
336                                 }
337                                 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){
338                                         yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value"));
339                                         yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units"));
340                                 }
341                                 yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start"));
342                                 yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end"));
343                         String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets());
344                        // Convert the  Policy into Stream input to Policy Adapter. 
345                         Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
346                                 return (PolicyType) policy;
347                         } catch (IOException e) {
348                                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e);
349                         }
350                 } catch (BuilderException e) {
351                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e);
352                         throw e;
353                 }
354                 return null;
355         }
356         
357         private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
358                 DecisionSettings decisionSetting = null;
359                 
360                 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
361                 Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll");
362                 List<?> decisionSettingsList = getDecisionSettings.getResultList();
363                 
364                 for (Object id : decisionSettingsList) {
365                         decisionSetting = (DecisionSettings) id;
366                         if (decisionSetting.getXacmlId().equals(settingId)) {
367                                 break;
368                         }
369                 }
370                 return decisionSetting;
371         }
372         
373         private void createRule(PolicyType decisionPolicy, boolean permitRule) {
374                 RuleType rule = new RuleType();
375                         
376                 rule.setRuleId(policyAdapter.getRuleID());
377                         
378                 if (permitRule) {
379                         rule.setEffect(EffectType.PERMIT);
380                 } else {
381                         rule.setEffect(EffectType.DENY);
382                 }
383                 rule.setTarget(new TargetType());
384
385                 // Create Target in Rule
386                 AllOfType allOfInRule = new AllOfType();
387
388                 // Creating match for ACCESS in rule target
389                 MatchType accessMatch = new MatchType();
390                 AttributeValueType accessAttributeValue = new AttributeValueType();
391                 accessAttributeValue.setDataType(STRING_DATATYPE);
392                 accessAttributeValue.getContent().add("DECIDE");
393                 accessMatch.setAttributeValue(accessAttributeValue);
394                 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
395                 URI accessURI = null;
396                 try {
397                         accessURI = new URI(ACTION_ID);
398                 } catch (URISyntaxException e) {
399                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
400                 }
401                 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
402                 accessAttributeDesignator.setDataType(STRING_DATATYPE);
403                 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
404                 accessMatch.setAttributeDesignator(accessAttributeDesignator);
405                 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
406                 
407                 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
408                 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
409                 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
410                 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
411                 dropDownMap = createDropDownMap();
412                 
413                 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
414                         // Values for AAF Provider are here for XML Creation. 
415                         ConditionType condition = new ConditionType();
416                         ApplyType decisionApply = new ApplyType();
417                         String selectedFunction = "boolean-equal";
418                         
419                         AttributeValueType value1 = new AttributeValueType();
420                         value1.setDataType(BOOLEAN_DATATYPE);
421                         value1.getContent().add("true");
422                         
423                         AttributeDesignatorType value2 = new AttributeDesignatorType();
424                         value2.setAttributeId(AAFEngine.AAF_RESULT);
425                         value2.setCategory(CATEGORY_RESOURCE);
426                         value2.setDataType(BOOLEAN_DATATYPE);
427                         value2.setMustBePresent(false);
428                         
429                         ApplyType innerDecisionApply = new ApplyType();
430                         innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
431                         innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
432                         
433                         decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
434                         decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
435                         decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
436                         condition.setExpression(new ObjectFactory().createApply(decisionApply));
437                         if (!permitRule) {
438                                 ApplyType notOuterApply = new ApplyType();
439                                 notOuterApply.setFunctionId(FUNCTION_NOT);
440                                 notOuterApply.getExpression().add(condition.getExpression());
441                                 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
442                         }
443                         rule.setCondition(condition);
444                         allOfInRule.getMatch().add(accessMatch);
445
446                         AnyOfType anyOfInRule = new AnyOfType();
447                         anyOfInRule.getAllOf().add(allOfInRule);
448
449                         TargetType targetInRule = new TargetType();
450                         targetInRule.getAnyOf().add(anyOfInRule);
451
452                         rule.setTarget(targetInRule);
453                         if(!permitRule){
454                                 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
455                                 AdviceExpressionType adviceExpression = new AdviceExpressionType();
456                                 adviceExpression.setAdviceId(AAFPROVIDER);
457                                 adviceExpression.setAppliesTo(EffectType.DENY);
458                                 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
459                                 assignment.setAttributeId("aaf.response");
460                                 assignment.setCategory(CATEGORY_RESOURCE);
461                                 AttributeDesignatorType value = new AttributeDesignatorType();
462                                 value.setAttributeId(AAFEngine.AAF_RESPONSE);
463                                 value.setCategory(CATEGORY_RESOURCE);
464                                 value.setDataType(STRING_DATATYPE);
465                                 value.setMustBePresent(false);
466                                 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
467                                 adviceExpression.getAttributeAssignmentExpression().add(assignment);
468                                 adviceExpressions.getAdviceExpression().add(adviceExpression);
469                                 rule.setAdviceExpressions(adviceExpressions);
470                         }
471                         decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
472                         policyAdapter.setPolicyData(decisionPolicy);
473                         
474                 }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
475                         boolean isCompound = false;
476                         ConditionType condition = new ConditionType();
477                         int index = dynamicFieldOneRuleAlgorithms.size() - 1;
478                         
479                         for (String labelAttr : dynamicLabelRuleAlgorithms) {
480                                 // if the rule algorithm as a label means it is a compound
481                                 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
482                                         ApplyType decisionApply = new ApplyType();
483
484                                         String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
485                                         String value1 = dynamicFieldOneRuleAlgorithms.get(index);
486                                         String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
487                                         decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
488                                         decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
489                                         decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
490                                         condition.setExpression(new ObjectFactory().createApply(decisionApply));
491                                         isCompound = true;
492                                 }
493
494                                 // if rule algorithm not a compound
495                                 if (!isCompound) {
496                                         condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
497                                 }
498                         }
499                         if (!permitRule) {
500                                 ApplyType notOuterApply = new ApplyType();
501                                 notOuterApply.setFunctionId(FUNCTION_NOT);
502                                 notOuterApply.getExpression().add(condition.getExpression());
503                                 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
504                         }
505                         rule.setCondition(condition);
506                         allOfInRule.getMatch().add(accessMatch);
507
508                         AnyOfType anyOfInRule = new AnyOfType();
509                         anyOfInRule.getAllOf().add(allOfInRule);
510
511                         TargetType targetInRule = new TargetType();
512                         targetInRule.getAnyOf().add(anyOfInRule);
513
514                         rule.setTarget(targetInRule);
515
516                         decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
517                         policyAdapter.setPolicyData(decisionPolicy);
518                         
519                 } else {
520                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName());
521                 }
522
523         }
524         
525         private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
526                 RuleType rule = new RuleType();
527                 
528                 rule.setRuleId(UUID.randomUUID().toString());
529                         
530                 if (permitRule) {
531                         rule.setEffect(EffectType.PERMIT);
532                 } else {
533                         rule.setEffect(EffectType.DENY);
534                 }
535                 rule.setTarget(new TargetType());
536
537                 // Create Target in Rule
538                 AllOfType allOfInRule = new AllOfType();
539
540                 // Creating match for DECIDE in rule target
541                 MatchType accessMatch = new MatchType();
542                 AttributeValueType accessAttributeValue = new AttributeValueType();
543                 accessAttributeValue.setDataType(STRING_DATATYPE);
544                 accessAttributeValue.getContent().add("DECIDE");
545                 accessMatch.setAttributeValue(accessAttributeValue);
546                 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
547                 URI accessURI = null;
548                 try {
549                         accessURI = new URI(ACTION_ID);
550                 } catch (URISyntaxException e) {
551                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
552                 }
553                 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
554                 accessAttributeDesignator.setDataType(STRING_DATATYPE);
555                 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
556                 accessMatch.setAttributeDesignator(accessAttributeDesignator);
557                 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
558                 
559                 allOfInRule.getMatch().add(accessMatch);
560                 
561                 // Creating match for ErrorCode in rule target
562                 MatchType errorcodeMatch = new MatchType();
563                 AttributeValueType errorcodeAttributeValue = new AttributeValueType();
564                 errorcodeAttributeValue.setDataType(STRING_DATATYPE);
565                 errorcodeAttributeValue.getContent().add(errorcode);
566                 errorcodeMatch.setAttributeValue(errorcodeAttributeValue);
567                 AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType();
568                 errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE);
569                 errorcodeAttributeDesignator.setDataType(STRING_DATATYPE);
570                 errorcodeAttributeDesignator.setAttributeId("ErrorCode");
571                 errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator);
572                 errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH);
573                 
574                 allOfInRule.getMatch().add(errorcodeMatch);
575                 
576                 AnyOfType anyOfInRule = new AnyOfType();
577                 anyOfInRule.getAllOf().add(allOfInRule);
578                 
579                 TargetType targetInRule = new TargetType();
580                 targetInRule.getAnyOf().add(anyOfInRule);
581                 
582                 rule.setTarget(targetInRule);
583                 
584                 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
585                 AdviceExpressionType adviceExpression = new AdviceExpressionType();             
586                 adviceExpression.setAdviceId(RAINY_DAY);
587                 adviceExpression.setAppliesTo(EffectType.PERMIT);
588                 
589                 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
590                 assignment.setAttributeId("treatment");
591                 assignment.setCategory(CATEGORY_RESOURCE);
592                 
593                 AttributeValueType treatmentAttributeValue = new AttributeValueType();
594                 treatmentAttributeValue.setDataType(STRING_DATATYPE);
595                 treatmentAttributeValue.getContent().add(treatment);
596                 assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
597                 
598                 adviceExpression.getAttributeAssignmentExpression().add(assignment);
599                 adviceExpressions.getAdviceExpression().add(adviceExpression);
600                 rule.setAdviceExpressions(adviceExpressions);
601                 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
602                 policyAdapter.setPolicyData(decisionPolicy);
603                 
604         }
605         
606         // if compound setting the inner apply here
607         protected ApplyType getInnerDecisionApply(String value1Label) {
608                 ApplyType decisionApply = new ApplyType();
609                 int index = 0;
610                 // check the index for the label.
611                 for (String labelAttr : dynamicLabelRuleAlgorithms) {
612                         if (labelAttr.equals(value1Label)) {
613                                 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
614                                 populateDataTypeList(value1);
615
616                                 // check if the row contains label again
617                                 for (String labelValue : dynamicLabelRuleAlgorithms) {
618                                         if (labelValue.equals(value1)) {
619                                                 return getCompoundDecisionApply(index);
620                                         }
621                                 }
622
623                                 // Getting the values from the form.
624                                 String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
625                                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
626                                 decisionApply.setFunctionId(dropDownMap.get(functionKey));
627                                 // if two text field are rule attributes.
628                                 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
629                                         ApplyType innerDecisionApply1 = new ApplyType();
630                                         ApplyType       innerDecisionApply2      = new  ApplyType();                                                      
631                                         AttributeDesignatorType  attributeDesignator1     = new AttributeDesignatorType();                                                               
632                                         AttributeDesignatorType  attributeDesignator2     = new AttributeDesignatorType();                                                                                       
633                                         //If selected function is Integer function set integer functionID
634                                         if(functionKey.toLowerCase().contains("integer")){
635                                                 innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY );
636                                                 innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
637                                                 attributeDesignator1.setDataType(INTEGER_DATATYPE);
638                                                 attributeDesignator2.setDataType(INTEGER_DATATYPE);
639                                         } else{
640                                                 //If selected function is not a Integer function set String functionID
641                                                 innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
642                                                 innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
643                                                 attributeDesignator1.setDataType(STRING_DATATYPE);
644                                                 attributeDesignator2.setDataType(STRING_DATATYPE);
645                                         }
646                                         attributeDesignator1.setCategory(CATEGORY_RESOURCE);
647                                         attributeDesignator2.setCategory(CATEGORY_RESOURCE);
648                                         //Here set actual field values
649                                         attributeDesignator1.setAttributeId(value1.  contains("resource:")?value1.substring( 9):value1.substring(8));
650                                         attributeDesignator2.setAttributeId(value1.  contains("resource:")?value1.substring( 9):value1.substring(8));                                                    
651                                         innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1));
652                                         innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2));                                                    
653                                         decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1));
654                                         decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2));                                                          
655                                 } else {
656                                         // if either of one text field is rule attribute.
657                                         if (!value1.startsWith("S_")) {
658                                                 ApplyType innerDecisionApply = new ApplyType();
659                                                 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
660                                                 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
661
662                                                 if (functionKey.toLowerCase().contains("integer")) {
663                                                         innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
664                                                         decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
665                                                         attributeDesignator.setDataType(INTEGER_DATATYPE);
666                                                 } else {
667                                                         innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
668                                                         decisionConditionAttributeValue.setDataType(STRING_DATATYPE);
669                                                         attributeDesignator.setDataType(STRING_DATATYPE);
670                                                 }
671
672                                                 String attributeId = null;
673                                                 String attributeValue = null;
674
675                                                 // Find which textField has rule attribute and set it as
676                                                 // attributeId and the other as attributeValue.
677                                                 attributeId = value1;
678                                                 attributeValue = value2;
679                         
680                                                 if (attributeId != null) {
681                                                         attributeDesignator.setCategory(CATEGORY_RESOURCE);
682                                                         attributeDesignator.setAttributeId(attributeId);
683                                                 }
684                                                 decisionConditionAttributeValue.getContent().add(attributeValue);
685                                                 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
686                                                 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
687                                                 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
688                                         } else {
689                                                 value1 = value1.substring(2, value1.length());
690                                                 VariableReferenceType variableReferenceType = new VariableReferenceType();
691                                                 variableReferenceType.setVariableId(value1);
692                                                 
693                                                 String dataType = dataTypeList.get(index);
694
695                                                 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
696                                                 decisionConditionAttributeValue.setDataType(dataType);
697                                                 decisionConditionAttributeValue.getContent().add(value2);
698                                                 decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType));
699                                                 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
700                                         }
701                                 }
702                         }
703                         index++;
704                 }
705                 return decisionApply;
706         }
707
708         // if the rule algorithm is multiple compound one setting the apply
709         protected ApplyType getCompoundDecisionApply(int index) {
710                 ApplyType decisionApply = new ApplyType();
711                 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
712                 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
713                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
714                 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
715                 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
716                 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
717                 return decisionApply;
718         }
719         
720         private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
721                 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
722                 AttributeValueType dynamicAttributeValue = new AttributeValueType();
723
724                 dynamicAttributeValue.setDataType(dataType);
725                 dynamicAttributeValue.getContent().add(value);
726
727                 dynamicVariable.setVariableId(key);
728                 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
729
730                 return dynamicVariable;
731
732         }       
733         
734         private void populateDataTypeList(String value1) {
735                 String dataType = null;
736                 if(value1.contains("S_")) {
737                         value1 = value1.substring(2, value1.length());
738                         DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
739                         if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
740                                 dataType = STRING_DATATYPE;
741                         } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
742                                 dataType = BOOLEAN_DATATYPE;
743                         } else {
744                                 dataType = INTEGER_DATATYPE;
745                         }
746                 } else {
747                         dataType = "OTHER";
748                 }
749
750                 dataTypeList.add(dataType);
751         }
752         
753         private Map<String,String> createDropDownMap(){
754                 JPAUtils jpaUtils = null;
755                 try {
756                         jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
757                 } catch (Exception e) {
758                         LOGGER.error("Exception Occured"+e);
759                 }
760                 Map<String, String> dropDownOptions = new HashMap<>();
761                 if(jpaUtils!=null){
762                         Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
763                         for (Map.Entry<Datatype,List<FunctionDefinition>> map: functionMap.entrySet()) {
764                                 for (FunctionDefinition functionDef : map.getValue()) {
765                                         dropDownOptions.put(functionDef.getShortname(),functionDef.getXacmlid());
766                                 }
767                         }
768                 }
769                 return dropDownOptions;
770         }
771         
772         private String getDataType(String key) {
773                 
774                 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
775                 String dataType = null;
776                 
777                 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
778                         dataType = STRING_DATATYPE;
779                 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
780                         dataType = BOOLEAN_DATATYPE;
781                 } else {
782                         dataType = INTEGER_DATATYPE;
783                 }
784                 
785                 return dataType;
786         }
787
788         @Override
789         public Object getCorrectPolicyDataObject() {
790                 return policyAdapter.getData();
791         }
792         
793 }