Merge "Add New Junit Tests For ONAP-XACML"
[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                                 dynamicFieldDecisionSettings = new HashMap<>();
235                         }
236                         
237                         // settings are dynamic so check how many rows are added and add all
238                         for (String keyField : dynamicFieldDecisionSettings.keySet()) {
239                                 String key = keyField;
240                                 String value = dynamicFieldDecisionSettings.get(key);
241                                 String dataType = getDataType(key);
242                                 VariableDefinitionType dynamicVariable = createDynamicVariable(key, value, dataType);
243                                 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(dynamicVariable);
244                         }
245                         Map<String, String> dynamicFieldTreatmentAttributes = policyAdapter.getRainydayMap();
246                         
247                         if(policyAdapter.getRuleProvider().equals(RAINY_DAY)){
248                                 for(String keyField : dynamicFieldTreatmentAttributes.keySet()) {
249                                         String errorcode = keyField;
250                                         String treatment = dynamicFieldTreatmentAttributes.get(errorcode);
251                                         createRainydayRule(decisionPolicy, errorcode, treatment, true);
252                                 }
253                         } else {
254                                 createRule(decisionPolicy, true);
255                                 createRule(decisionPolicy, false);
256                         }
257
258                 }
259                 setPreparedToSave(true);
260                 return true;
261         }
262         
263         public PolicyType getGuardPolicy(Map<String, String> yamlParams, String ruleProvider) throws BuilderException{
264                 try {
265                         ControlLoopGuardBuilder builder = ControlLoopGuardBuilder.Factory.buildControlLoopGuard(new Guard());
266                         MatchParameters matchParameters = new MatchParameters(yamlParams.get("actor"), yamlParams.get("recipe"));
267                         matchParameters.setControlLoopName(yamlParams.get("clname"));
268                         if(yamlParams.containsKey("targets")){
269                                 String targetString = yamlParams.get("targets");
270                                 List<String> targets = null;
271                                 if(targetString!=null && !targetString.isEmpty()){
272                                         if (targetString.contains(",")){
273                                                 targets = Arrays.asList(targetString.split(","));
274                                         }
275                                         else{
276                                                 targets = new ArrayList<>();
277                                                 targets.add(targetString);
278                                         }       
279                                 }
280                                 matchParameters.setTargets(targets);
281                         }
282                         GuardPolicy policy1 = new GuardPolicy((policyAdapter.getUuid()!=null? policyAdapter.getUuid(): UUID.randomUUID().toString()) ,yamlParams.get(POLICY_NAME), yamlParams.get(DESCRIPTION), matchParameters);
283                         builder = builder.addGuardPolicy(policy1);
284             Map<String, String> activeTimeRange = new HashMap<>();
285             activeTimeRange.put("start", yamlParams.get("guardActiveStart"));
286             activeTimeRange.put("end", yamlParams.get("guardActiveEnd"));
287                         String blackListString = yamlParams.get("blackList");
288                         List<String> blackList = null;
289             if(blackListString!=null && !blackListString.trim().isEmpty()){
290                                 if (blackListString.contains(",")){
291                                         blackList = Arrays.asList(blackListString.split(","));                                                          
292                                 }
293                                 else{
294                                         blackList = new ArrayList<>();
295                                         blackList.add(blackListString);
296                                 }       
297                         }
298                         File templateFile;
299                         Path xacmlTemplatePath;
300                         ClassLoader classLoader = getClass().getClassLoader();
301                         Constraint cons = new Constraint();
302                         switch (ruleProvider){
303                         case GUARD_BL_YAML:
304                                 templateFile = new File(classLoader.getResource(XACML_BLGUARD_TEMPLATE).getFile());
305                                 xacmlTemplatePath = templateFile.toPath();
306                 cons.setActive_time_range(activeTimeRange);
307                 if(blackList==null || blackList.isEmpty()){
308                     throw new BuilderException("blackList is required");
309                 }
310                 cons.setBlacklist(blackList);
311                                 break;
312                         default:
313                                 templateFile = new File(classLoader.getResource(XACML_GUARD_TEMPLATE).getFile());
314                                 xacmlTemplatePath = templateFile.toPath();
315                                 Map<String,String> timeWindow = new HashMap<>();
316                                 if(!PolicyUtils.isInteger(yamlParams.get("timeWindow"))){
317                                         throw new BuilderException("time window is not in Integer format.");
318                                 }
319                                 String timeUnits = yamlParams.get("timeUnits");
320                                 if(timeUnits==null || !(timeUnits.equalsIgnoreCase("minute") || timeUnits.equalsIgnoreCase("hour") || timeUnits.equalsIgnoreCase("day") 
321                                                 || timeUnits.equalsIgnoreCase("week") || timeUnits.equalsIgnoreCase("month")||timeUnits.equalsIgnoreCase("year"))){
322                                         throw new BuilderException("time Units is not in proper format.");
323                                 }
324                                 timeWindow.put("value", yamlParams.get("timeWindow"));
325                                 timeWindow.put("units", yamlParams.get("timeUnits"));
326                                 cons = new Constraint(Integer.parseInt(yamlParams.get("limit")),timeWindow,activeTimeRange);
327                                 break;
328                         }
329                         builder = builder.addLimitConstraint(policy1.getId(), cons);
330                         // Build the specification
331                         Results results = builder.buildSpecification();
332                         // YAML TO XACML 
333                         ControlLoopGuard yamlGuardObject = SafePolicyBuilder.loadYamlGuard(results.getSpecification());
334                 String xacmlTemplateContent;
335                 try {
336                                 xacmlTemplateContent = new String(Files.readAllBytes(xacmlTemplatePath));
337                                 HashMap<String, String> yamlSpecs = new HashMap<>();
338                                 yamlSpecs.put(POLICY_NAME, yamlParams.get(POLICY_NAME));
339                                 yamlSpecs.put(DESCRIPTION, yamlParams.get(DESCRIPTION));
340                                 yamlSpecs.put(ONAPNAME, yamlParams.get(ONAPNAME));
341                                 yamlSpecs.put("actor", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getActor());
342                                 yamlSpecs.put("recipe", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getRecipe());
343                                 yamlSpecs.put("clname", yamlGuardObject.getGuards().getFirst().getMatch_parameters().getControlLoopName());
344                                 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target()!=null){
345                                         yamlSpecs.put("limit", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getFreq_limit_per_target().toString());
346                                 }
347                                 if(yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window()!=null){
348                                         yamlSpecs.put("twValue", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("value"));
349                                         yamlSpecs.put("twUnits", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getTime_window().get("units"));
350                                 }
351                                 yamlSpecs.put("guardActiveStart", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("start"));
352                                 yamlSpecs.put("guardActiveEnd", yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getActive_time_range().get("end"));
353                         String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent,yamlSpecs, yamlGuardObject.getGuards().getFirst().getLimit_constraints().getFirst().getBlacklist(), yamlGuardObject.getGuards().getFirst().getMatch_parameters().getTargets());
354                        // Convert the  Policy into Stream input to Policy Adapter. 
355                         Object policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(xacmlPolicyContent.getBytes(StandardCharsets.UTF_8)));
356                                 return (PolicyType) policy;
357                         } catch (IOException e) {
358                                 LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() , e);
359                         }
360                 } catch (BuilderException e) {
361                         LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error while creating the policy " + e.getMessage() ,e);
362                         throw e;
363                 }
364                 return null;
365         }
366         
367         private DecisionSettings findDecisionSettingsBySettingId(String settingId) {
368                 DecisionSettings decisionSetting = null;
369                 
370                 EntityManager em = XACMLPapServlet.getEmf().createEntityManager();
371                 Query getDecisionSettings = em.createNamedQuery("DecisionSettings.findAll");
372                 List<?> decisionSettingsList = getDecisionSettings.getResultList();
373                 
374                 for (Object id : decisionSettingsList) {
375                         decisionSetting = (DecisionSettings) id;
376                         if (decisionSetting.getXacmlId().equals(settingId)) {
377                                 break;
378                         }
379                 }
380                 return decisionSetting;
381         }
382         
383         private void createRule(PolicyType decisionPolicy, boolean permitRule) {
384                 RuleType rule = new RuleType();
385                         
386                 rule.setRuleId(policyAdapter.getRuleID());
387                         
388                 if (permitRule) {
389                         rule.setEffect(EffectType.PERMIT);
390                 } else {
391                         rule.setEffect(EffectType.DENY);
392                 }
393                 rule.setTarget(new TargetType());
394
395                 // Create Target in Rule
396                 AllOfType allOfInRule = new AllOfType();
397
398                 // Creating match for ACCESS in rule target
399                 MatchType accessMatch = new MatchType();
400                 AttributeValueType accessAttributeValue = new AttributeValueType();
401                 accessAttributeValue.setDataType(STRING_DATATYPE);
402                 accessAttributeValue.getContent().add("DECIDE");
403                 accessMatch.setAttributeValue(accessAttributeValue);
404                 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
405                 URI accessURI = null;
406                 try {
407                         accessURI = new URI(ACTION_ID);
408                 } catch (URISyntaxException e) {
409                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
410                 }
411                 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
412                 accessAttributeDesignator.setDataType(STRING_DATATYPE);
413                 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
414                 accessMatch.setAttributeDesignator(accessAttributeDesignator);
415                 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
416                 
417                 dynamicLabelRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmLabels();
418                 dynamicFieldComboRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmCombo();
419                 dynamicFieldOneRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField1();
420                 dynamicFieldTwoRuleAlgorithms = policyAdapter.getDynamicRuleAlgorithmField2();
421                 dropDownMap = createDropDownMap();
422                 
423                 if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals(AAFPROVIDER)){
424                         // Values for AAF Provider are here for XML Creation. 
425                         ConditionType condition = new ConditionType();
426                         ApplyType decisionApply = new ApplyType();
427                         
428                         AttributeValueType value1 = new AttributeValueType();
429                         value1.setDataType(BOOLEAN_DATATYPE);
430                         value1.getContent().add("true");
431                         
432                         AttributeDesignatorType value2 = new AttributeDesignatorType();
433                         value2.setAttributeId(AAFEngine.AAF_RESULT);
434                         value2.setCategory(CATEGORY_RESOURCE);
435                         value2.setDataType(BOOLEAN_DATATYPE);
436                         value2.setMustBePresent(false);
437                         
438                         ApplyType innerDecisionApply = new ApplyType();
439                         innerDecisionApply.setFunctionId(FUNCTION_BOOLEAN_ONE_AND_ONLY);
440                         innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(value2));
441                         
442                         decisionApply.setFunctionId(XACML3.ID_FUNCTION_BOOLEAN_EQUAL.stringValue());
443                         decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(value1));
444                         decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
445                         condition.setExpression(new ObjectFactory().createApply(decisionApply));
446                         if (!permitRule) {
447                                 ApplyType notOuterApply = new ApplyType();
448                                 notOuterApply.setFunctionId(FUNCTION_NOT);
449                                 notOuterApply.getExpression().add(condition.getExpression());
450                                 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
451                         }
452                         rule.setCondition(condition);
453                         allOfInRule.getMatch().add(accessMatch);
454
455                         AnyOfType anyOfInRule = new AnyOfType();
456                         anyOfInRule.getAllOf().add(allOfInRule);
457
458                         TargetType targetInRule = new TargetType();
459                         targetInRule.getAnyOf().add(anyOfInRule);
460
461                         rule.setTarget(targetInRule);
462                         if(!permitRule){
463                                 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
464                                 AdviceExpressionType adviceExpression = new AdviceExpressionType();
465                                 adviceExpression.setAdviceId(AAFPROVIDER);
466                                 adviceExpression.setAppliesTo(EffectType.DENY);
467                                 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
468                                 assignment.setAttributeId("aaf.response");
469                                 assignment.setCategory(CATEGORY_RESOURCE);
470                                 AttributeDesignatorType value = new AttributeDesignatorType();
471                                 value.setAttributeId(AAFEngine.AAF_RESPONSE);
472                                 value.setCategory(CATEGORY_RESOURCE);
473                                 value.setDataType(STRING_DATATYPE);
474                                 value.setMustBePresent(false);
475                                 assignment.setExpression(new ObjectFactory().createAttributeDesignator(value));
476                                 adviceExpression.getAttributeAssignmentExpression().add(assignment);
477                                 adviceExpressions.getAdviceExpression().add(adviceExpression);
478                                 rule.setAdviceExpressions(adviceExpressions);
479                         }
480                         decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
481                         policyAdapter.setPolicyData(decisionPolicy);
482                         
483                 }else if (dynamicLabelRuleAlgorithms != null && !dynamicLabelRuleAlgorithms.isEmpty()) {
484                         boolean isCompound = false;
485                         ConditionType condition = new ConditionType();
486                         int index = dynamicFieldOneRuleAlgorithms.size() - 1;
487                         
488                         for (String labelAttr : dynamicLabelRuleAlgorithms) {
489                                 // if the rule algorithm as a label means it is a compound
490                                 if (dynamicFieldOneRuleAlgorithms.get(index).equals(labelAttr)) {
491                                         ApplyType decisionApply = new ApplyType();
492
493                                         String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
494                                         String value1 = dynamicFieldOneRuleAlgorithms.get(index);
495                                         String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
496                                         decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
497                                         decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
498                                         decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
499                                         condition.setExpression(new ObjectFactory().createApply(decisionApply));
500                                         isCompound = true;
501                                 }
502
503                                 // if rule algorithm not a compound
504                                 if (!isCompound) {
505                                         condition.setExpression(new ObjectFactory().createApply(getInnerDecisionApply(dynamicLabelRuleAlgorithms.get(index))));
506                                 }
507                         }
508                         if (!permitRule) {
509                                 ApplyType notOuterApply = new ApplyType();
510                                 notOuterApply.setFunctionId(FUNCTION_NOT);
511                                 notOuterApply.getExpression().add(condition.getExpression());
512                                 condition.setExpression(new ObjectFactory().createApply(notOuterApply));
513                         }
514                         rule.setCondition(condition);
515                         allOfInRule.getMatch().add(accessMatch);
516
517                         AnyOfType anyOfInRule = new AnyOfType();
518                         anyOfInRule.getAllOf().add(allOfInRule);
519
520                         TargetType targetInRule = new TargetType();
521                         targetInRule.getAnyOf().add(anyOfInRule);
522
523                         rule.setTarget(targetInRule);
524
525                         decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
526                         policyAdapter.setPolicyData(decisionPolicy);
527                         
528                 } else {
529                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + "Unsupported data object."+ policyAdapter.getData().getClass().getCanonicalName());
530                 }
531
532         }
533         
534         private void createRainydayRule(PolicyType decisionPolicy, String errorcode, String treatment, boolean permitRule) {
535                 RuleType rule = new RuleType();
536                 
537                 rule.setRuleId(UUID.randomUUID().toString());
538                         
539                 if (permitRule) {
540                         rule.setEffect(EffectType.PERMIT);
541                 } else {
542                         rule.setEffect(EffectType.DENY);
543                 }
544                 rule.setTarget(new TargetType());
545
546                 // Create Target in Rule
547                 AllOfType allOfInRule = new AllOfType();
548
549                 // Creating match for DECIDE in rule target
550                 MatchType accessMatch = new MatchType();
551                 AttributeValueType accessAttributeValue = new AttributeValueType();
552                 accessAttributeValue.setDataType(STRING_DATATYPE);
553                 accessAttributeValue.getContent().add("DECIDE");
554                 accessMatch.setAttributeValue(accessAttributeValue);
555                 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
556                 URI accessURI = null;
557                 try {
558                         accessURI = new URI(ACTION_ID);
559                 } catch (URISyntaxException e) {
560                         PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "DecisionPolicy", "Exception creating ACCESS URI");
561                 }
562                 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
563                 accessAttributeDesignator.setDataType(STRING_DATATYPE);
564                 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
565                 accessMatch.setAttributeDesignator(accessAttributeDesignator);
566                 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
567                 
568                 allOfInRule.getMatch().add(accessMatch);
569                 
570                 // Creating match for ErrorCode in rule target
571                 MatchType errorcodeMatch = new MatchType();
572                 AttributeValueType errorcodeAttributeValue = new AttributeValueType();
573                 errorcodeAttributeValue.setDataType(STRING_DATATYPE);
574                 errorcodeAttributeValue.getContent().add(errorcode);
575                 errorcodeMatch.setAttributeValue(errorcodeAttributeValue);
576                 AttributeDesignatorType errorcodeAttributeDesignator = new AttributeDesignatorType();
577                 errorcodeAttributeDesignator.setCategory(CATEGORY_RESOURCE);
578                 errorcodeAttributeDesignator.setDataType(STRING_DATATYPE);
579                 errorcodeAttributeDesignator.setAttributeId("ErrorCode");
580                 errorcodeMatch.setAttributeDesignator(errorcodeAttributeDesignator);
581                 errorcodeMatch.setMatchId(FUNCTION_STRING_REGEXP_MATCH);
582                 
583                 allOfInRule.getMatch().add(errorcodeMatch);
584                 
585                 AnyOfType anyOfInRule = new AnyOfType();
586                 anyOfInRule.getAllOf().add(allOfInRule);
587                 
588                 TargetType targetInRule = new TargetType();
589                 targetInRule.getAnyOf().add(anyOfInRule);
590                 
591                 rule.setTarget(targetInRule);
592                 
593                 AdviceExpressionsType adviceExpressions = new AdviceExpressionsType();
594                 AdviceExpressionType adviceExpression = new AdviceExpressionType();             
595                 adviceExpression.setAdviceId(RAINY_DAY);
596                 adviceExpression.setAppliesTo(EffectType.PERMIT);
597                 
598                 AttributeAssignmentExpressionType assignment = new AttributeAssignmentExpressionType();
599                 assignment.setAttributeId("treatment");
600                 assignment.setCategory(CATEGORY_RESOURCE);
601                 
602                 AttributeValueType treatmentAttributeValue = new AttributeValueType();
603                 treatmentAttributeValue.setDataType(STRING_DATATYPE);
604                 treatmentAttributeValue.getContent().add(treatment);
605                 assignment.setExpression(new ObjectFactory().createAttributeValue(treatmentAttributeValue));
606                 
607                 adviceExpression.getAttributeAssignmentExpression().add(assignment);
608                 adviceExpressions.getAdviceExpression().add(adviceExpression);
609                 rule.setAdviceExpressions(adviceExpressions);
610                 decisionPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
611                 policyAdapter.setPolicyData(decisionPolicy);
612                 
613         }
614         
615         // if compound setting the inner apply here
616         protected ApplyType getInnerDecisionApply(String value1Label) {
617                 ApplyType decisionApply = new ApplyType();
618                 int index = 0;
619                 // check the index for the label.
620                 for (String labelAttr : dynamicLabelRuleAlgorithms) {
621                         if (labelAttr.equals(value1Label)) {
622                                 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
623                                 populateDataTypeList(value1);
624
625                                 // check if the row contains label again
626                                 for (String labelValue : dynamicLabelRuleAlgorithms) {
627                                         if (labelValue.equals(value1)) {
628                                                 return getCompoundDecisionApply(index);
629                                         }
630                                 }
631
632                                 // Getting the values from the form.
633                                 String functionKey = dynamicFieldComboRuleAlgorithms.get(index);
634                                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
635                                 decisionApply.setFunctionId(dropDownMap.get(functionKey));
636                                 // if two text field are rule attributes.
637                                 if ((value1.contains(RULE_VARIABLE)) && (value2.contains(RULE_VARIABLE))) {
638                                         ApplyType innerDecisionApply1 = new ApplyType();
639                                         ApplyType       innerDecisionApply2      = new  ApplyType();                                                      
640                                         AttributeDesignatorType  attributeDesignator1     = new AttributeDesignatorType();                                                               
641                                         AttributeDesignatorType  attributeDesignator2     = new AttributeDesignatorType();                                                                                       
642                                         //If selected function is Integer function set integer functionID
643                                         if(functionKey.toLowerCase().contains("integer")){
644                                                 innerDecisionApply1.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY );
645                                                 innerDecisionApply2.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
646                                                 attributeDesignator1.setDataType(INTEGER_DATATYPE);
647                                                 attributeDesignator2.setDataType(INTEGER_DATATYPE);
648                                         } else{
649                                                 //If selected function is not a Integer function set String functionID
650                                                 innerDecisionApply1.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
651                                                 innerDecisionApply2.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
652                                                 attributeDesignator1.setDataType(STRING_DATATYPE);
653                                                 attributeDesignator2.setDataType(STRING_DATATYPE);
654                                         }
655                                         attributeDesignator1.setCategory(CATEGORY_RESOURCE);
656                                         attributeDesignator2.setCategory(CATEGORY_RESOURCE);
657                                         //Here set actual field values
658                                         attributeDesignator1.setAttributeId(value1.  contains("resource:")?value1.substring( 9):value1.substring(8));
659                                         attributeDesignator2.setAttributeId(value1.  contains("resource:")?value1.substring( 9):value1.substring(8));                                                    
660                                         innerDecisionApply1.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator1));
661                                         innerDecisionApply2.getExpression().add(new ObjectFactory().createAttributeDesignator( attributeDesignator2));                                                    
662                                         decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply1));
663                                         decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply2));                                                          
664                                 } else {
665                                         // if either of one text field is rule attribute.
666                                         if (!value1.startsWith("S_")) {
667                                                 ApplyType innerDecisionApply = new ApplyType();
668                                                 AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
669                                                 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
670
671                                                 if (functionKey.toLowerCase().contains("integer")) {
672                                                         innerDecisionApply.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY);
673                                                         decisionConditionAttributeValue.setDataType(INTEGER_DATATYPE);
674                                                         attributeDesignator.setDataType(INTEGER_DATATYPE);
675                                                 } else {
676                                                         innerDecisionApply.setFunctionId(FUNCTION_STRING_ONE_AND_ONLY);
677                                                         decisionConditionAttributeValue.setDataType(STRING_DATATYPE);
678                                                         attributeDesignator.setDataType(STRING_DATATYPE);
679                                                 }
680
681                                                 String attributeId = null;
682                                                 String attributeValue = null;
683
684                                                 // Find which textField has rule attribute and set it as
685                                                 // attributeId and the other as attributeValue.
686                                                 attributeId = value1;
687                                                 attributeValue = value2;
688                         
689                                                 if (attributeId != null) {
690                                                         attributeDesignator.setCategory(CATEGORY_RESOURCE);
691                                                         attributeDesignator.setAttributeId(attributeId);
692                                                 }
693                                                 decisionConditionAttributeValue.getContent().add(attributeValue);
694                                                 innerDecisionApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator));
695                                                 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
696                                                 decisionApply.getExpression().add(new ObjectFactory().createApply(innerDecisionApply));
697                                         } else {
698                                                 value1 = value1.substring(2, value1.length());
699                                                 VariableReferenceType variableReferenceType = new VariableReferenceType();
700                                                 variableReferenceType.setVariableId(value1);
701                                                 
702                                                 String dataType = dataTypeList.get(index);
703
704                                                 AttributeValueType decisionConditionAttributeValue = new AttributeValueType();
705                                                 decisionConditionAttributeValue.setDataType(dataType);
706                                                 decisionConditionAttributeValue.getContent().add(value2);
707                                                 decisionApply.getExpression().add(new ObjectFactory().createVariableReference(variableReferenceType));
708                                                 decisionApply.getExpression().add(new ObjectFactory().createAttributeValue(decisionConditionAttributeValue));
709                                         }
710                                 }
711                         }
712                         index++;
713                 }
714                 return decisionApply;
715         }
716
717         // if the rule algorithm is multiple compound one setting the apply
718         protected ApplyType getCompoundDecisionApply(int index) {
719                 ApplyType decisionApply = new ApplyType();
720                 String selectedFunction = dynamicFieldComboRuleAlgorithms.get(index);
721                 String value1 = dynamicFieldOneRuleAlgorithms.get(index);
722                 String value2 = dynamicFieldTwoRuleAlgorithms.get(index);
723                 decisionApply.setFunctionId(dropDownMap.get(selectedFunction));
724                 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value1)));
725                 decisionApply.getExpression().add(new ObjectFactory().createApply(getInnerDecisionApply(value2)));
726                 return decisionApply;
727         }
728         
729         private VariableDefinitionType createDynamicVariable(String key, String value, String dataType) {
730                 VariableDefinitionType dynamicVariable = new VariableDefinitionType();
731                 AttributeValueType dynamicAttributeValue = new AttributeValueType();
732
733                 dynamicAttributeValue.setDataType(dataType);
734                 dynamicAttributeValue.getContent().add(value);
735
736                 dynamicVariable.setVariableId(key);
737                 dynamicVariable.setExpression(new ObjectFactory().createAttributeValue(dynamicAttributeValue));
738
739                 return dynamicVariable;
740
741         }       
742         
743         private void populateDataTypeList(String value1) {
744                 String dataType = null;
745                 if(value1.contains("S_")) {
746                         value1 = value1.substring(2, value1.length());
747                         DecisionSettings decisionSettings = findDecisionSettingsBySettingId(value1.substring(2, value1.length()));
748                         if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
749                                 dataType = STRING_DATATYPE;
750                         } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
751                                 dataType = BOOLEAN_DATATYPE;
752                         } else {
753                                 dataType = INTEGER_DATATYPE;
754                         }
755                 } else {
756                         dataType = "OTHER";
757                 }
758
759                 dataTypeList.add(dataType);
760         }
761         
762         private Map<String,String> createDropDownMap(){
763                 JPAUtils jpaUtils = null;
764                 try {
765                         jpaUtils = JPAUtils.getJPAUtilsInstance(XACMLPapServlet.getEmf());
766                 } catch (Exception e) {
767                         LOGGER.error("Exception Occured"+e);
768                 }
769                 Map<String, String> dropDownOptions = new HashMap<>();
770                 if(jpaUtils!=null){
771                         Map<Datatype, List<FunctionDefinition>> functionMap = jpaUtils.getFunctionDatatypeMap();
772                         for (Map.Entry<Datatype,List<FunctionDefinition>> map: functionMap.entrySet()) {
773                                 for (FunctionDefinition functionDef : map.getValue()) {
774                                         dropDownOptions.put(functionDef.getShortname(),functionDef.getXacmlid());
775                                 }
776                         }
777                 }
778                 return dropDownOptions;
779         }
780         
781         private String getDataType(String key) {
782                 
783                 DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
784                 String dataType = null;
785                 
786                 if (decisionSettings != null && "string".equals(decisionSettings.getDatatypeBean().getShortName())) {
787                         dataType = STRING_DATATYPE;
788                 } else if (decisionSettings != null && "boolean".equals(decisionSettings.getDatatypeBean().getShortName())) {
789                         dataType = BOOLEAN_DATATYPE;
790                 } else {
791                         dataType = INTEGER_DATATYPE;
792                 }
793                 
794                 return dataType;
795         }
796
797         @Override
798         public Object getCorrectPolicyDataObject() {
799                 return policyAdapter.getData();
800         }
801         
802 }