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