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