Commit includes ControlLoopPolicy API and bugfixes
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / components / CreateBrmsRawPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-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.openecomp.policy.pap.xacml.rest.components;
22
23
24 import java.io.File;
25 import java.io.IOException;
26 import java.io.PrintWriter;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.nio.charset.Charset;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.util.ArrayList;
34 import java.util.HashMap;
35 import java.util.Map;
36
37 import org.apache.commons.io.FilenameUtils;
38 import org.openecomp.policy.common.logging.eelf.MessageCodes;
39 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
40 import org.openecomp.policy.pap.xacml.rest.controller.BRMSDictionaryController;
41 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
42
43 import com.att.research.xacml.std.IdentifierImpl;
44
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
58
59
60 public class CreateBrmsRawPolicy extends Policy {
61         
62         public CreateBrmsRawPolicy() {
63                 super();
64         }
65
66         public CreateBrmsRawPolicy(PolicyRestAdapter policyAdapter) {
67                 this.policyAdapter = policyAdapter;
68                 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
69
70         }
71
72         // Saving the Configurations file at server location for CreateBrmsRawPolicy policy.
73         protected void saveConfigurations(String policyName, String jsonBody) {         
74                 try {
75                         if (policyName.endsWith(".xml")) {
76                                 policyName = policyName.substring(0,
77                                                 policyName.lastIndexOf(".xml"));
78                         }
79                         PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt");
80                         out.println(jsonBody);
81                         out.close();
82
83                 } catch (Exception e) {
84                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy", "Exception saving configurations file");
85                 }
86         }
87
88         // Utility to read json data from the existing file to a string
89         static String readFile(String path, Charset encoding) throws IOException {
90
91                 byte[] encoded = Files.readAllBytes(Paths.get(path));
92                 return new String(encoded, encoding);
93
94         }
95
96         // Here we are adding the extension for the configurations file based on the
97         // config type selection for saving.
98         private String getConfigFile(String filename) {
99                 filename = FilenameUtils.removeExtension(filename);
100                 if (filename.endsWith(".txt")) {
101                         filename = filename.substring(0, filename.length() - 3);
102                 }
103
104                 filename = filename + ".txt";
105                 return filename;
106         }
107
108         // Validations for Config form
109         public boolean validateConfigForm() {
110
111                 // Validating mandatory Fields.
112                 isValidForm = true;
113                 return isValidForm;
114
115         }
116
117         @Override
118         public Map<String, String> savePolicies() throws Exception {
119                 
120                 Map<String, String> successMap = new HashMap<>();
121                 if(isPolicyExists()){
122                         successMap.put("EXISTS", "This Policy already exist on the PAP");
123                         return successMap;
124                 }
125                 
126                 if (!isPreparedToSave()) {
127                         prepareToSave();
128                 }
129                 // Until here we prepared the data and here calling the method to create
130                 // xml.
131                 Path newPolicyPath = null;
132                 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
133                 
134                 Boolean dbIsUpdated = true;
135
136                 successMap = new HashMap<String, String>();
137                 if (dbIsUpdated) {
138                         successMap = createPolicy(newPolicyPath,
139                                         getCorrectPolicyDataObject());
140                 } else {
141                         PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
142                         successMap.put("error", "DB UPDATE");
143                 }
144
145                 return successMap;
146         }
147
148         // This is the method for preparing the policy for saving. We have broken it
149         // out
150         // separately because the fully configured policy is used for multiple
151         // things
152         @Override
153         public boolean prepareToSave() throws Exception {
154
155                 if (isPreparedToSave()) {
156                         // we have already done this
157                         return true;
158                 }
159
160                 int version = 0;
161                 String policyID = policyAdapter.getPolicyID();
162                 version = policyAdapter.getHighestVersion();
163
164                 // Create the Instance for pojo, PolicyType object is used in
165                 // marshalling.
166                 if (policyAdapter.getPolicyType().equals("Config")) {
167                         PolicyType policyConfig = new PolicyType();
168
169                         policyConfig.setVersion(Integer.toString(version));
170                         policyConfig.setPolicyId(policyID);
171                         policyConfig.setTarget(new TargetType());
172                         policyAdapter.setData(policyConfig);
173                 }
174
175                 policyName = policyAdapter.getNewFileName();
176                 
177                 if (policyAdapter.getData() != null) {
178                         //String jsonBody = policyAdapter.getJsonBody();
179                         String configBody=policyAdapter.getConfigBodyData();
180                         saveConfigurations(policyName, configBody);
181
182                         // Make sure the filename ends with an extension
183                         if (policyName.endsWith(".xml") == false) {
184                                 policyName = policyName + ".xml";
185                         }
186
187                         PolicyType configPolicy = (PolicyType) policyAdapter.getData();
188
189                         configPolicy.setDescription(policyAdapter.getPolicyDescription());
190
191                         configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
192
193                         AllOfType allOfOne = new AllOfType();
194                         String fileName = policyAdapter.getNewFileName();
195                         String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
196                         if ((name == null) || (name.equals(""))) {
197                                 name = fileName.substring(fileName.lastIndexOf("/") + 1,
198                                                 fileName.length());
199                         }
200                         allOfOne.getMatch().add(createMatch("PolicyName", name));
201                         
202                         
203                         AllOfType allOf = new AllOfType();
204
205                         // Match for ECOMPName
206                         allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName()));
207                         allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
208                         // Match for riskType
209                         allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
210                         // Match for riskLevel
211                         allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
212                         // Match for riskguard
213                         allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
214                         // Match for ttlDate
215                         allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
216                         AnyOfType anyOf = new AnyOfType();
217                         anyOf.getAllOf().add(allOfOne);
218                         anyOf.getAllOf().add(allOf);
219
220                         TargetType target = new TargetType();
221                         ((TargetType) target).getAnyOf().add(anyOf);
222
223                         // Adding the target to the policy element
224                         configPolicy.setTarget((TargetType) target);
225
226                         RuleType rule = new RuleType();
227                         rule.setRuleId(policyAdapter.getRuleID());
228
229                         rule.setEffect(EffectType.PERMIT);
230
231                         // Create Target in Rule
232                         AllOfType allOfInRule = new AllOfType();
233
234                         // Creating match for ACCESS in rule target
235                         MatchType accessMatch = new MatchType();
236                         AttributeValueType accessAttributeValue = new AttributeValueType();
237                         accessAttributeValue.setDataType(STRING_DATATYPE);
238                         accessAttributeValue.getContent().add("ACCESS");
239                         accessMatch.setAttributeValue(accessAttributeValue);
240                         AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
241                         URI accessURI = null;
242                         try {
243                                 accessURI = new URI(ACTION_ID);
244                         } catch (URISyntaxException e) {
245                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating ACCESS URI");
246                         }
247                         accessAttributeDesignator.setCategory(CATEGORY_ACTION);
248                         accessAttributeDesignator.setDataType(STRING_DATATYPE);
249                         accessAttributeDesignator.setAttributeId(new IdentifierImpl(
250                                         accessURI).stringValue());
251                         accessMatch.setAttributeDesignator(accessAttributeDesignator);
252                         accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
253
254                         // Creating Config Match in rule Target
255                         MatchType configMatch = new MatchType();
256                         AttributeValueType configAttributeValue = new AttributeValueType();
257                         configAttributeValue.setDataType(STRING_DATATYPE);
258
259                         configAttributeValue.getContent().add("Config");
260
261                         configMatch.setAttributeValue(configAttributeValue);
262                         AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
263                         URI configURI = null;
264                         try {
265                                 configURI = new URI(RESOURCE_ID);
266                         } catch (URISyntaxException e) {
267                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating Config URI");
268                         }
269
270                         configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
271                         configAttributeDesignator.setDataType(STRING_DATATYPE);
272                         configAttributeDesignator.setAttributeId(new IdentifierImpl(
273                                         configURI).stringValue());
274                         configMatch.setAttributeDesignator(configAttributeDesignator);
275                         configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
276
277                         allOfInRule.getMatch().add(accessMatch);
278                         allOfInRule.getMatch().add(configMatch);
279
280                         AnyOfType anyOfInRule = new AnyOfType();
281                         anyOfInRule.getAllOf().add(allOfInRule);
282
283                         TargetType targetInRule = new TargetType();
284                         targetInRule.getAnyOf().add(anyOfInRule);
285
286                         rule.setTarget(targetInRule);
287                         rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
288
289                         configPolicy
290                                         .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
291                                         .add(rule);
292                         policyAdapter.setPolicyData(configPolicy);
293
294                 } else {
295                         PolicyLogger.error("Unsupported data object."
296                                         + policyAdapter.getData().getClass().getCanonicalName());
297                 }
298                 setPreparedToSave(true);
299                 return true;
300         }
301
302         // Data required for Advice part is setting here.
303         private AdviceExpressionsType getAdviceExpressions(int version,
304                         String fileName) {
305
306                 // Policy Config ID Assignment
307                 AdviceExpressionsType advices = new AdviceExpressionsType();
308                 AdviceExpressionType advice = new AdviceExpressionType();
309                 advice.setAdviceId("BRMSRAWID");
310                 advice.setAppliesTo(EffectType.PERMIT);
311                 // For Configuration
312                 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
313                 assignment1.setAttributeId("type");
314                 assignment1.setCategory(CATEGORY_RESOURCE);
315                 assignment1.setIssuer("");
316                 AttributeValueType configNameAttributeValue = new AttributeValueType();
317                 configNameAttributeValue.setDataType(STRING_DATATYPE);
318                 configNameAttributeValue.getContent().add("Configuration");
319                 assignment1.setExpression(new ObjectFactory()
320                                 .createAttributeValue(configNameAttributeValue));
321                 advice.getAttributeAssignmentExpression().add(assignment1);
322
323                 // For Config file Url if configurations are provided.
324                 // URL ID Assignment
325                 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
326                 assignment2.setAttributeId("URLID");
327                 assignment2.setCategory(CATEGORY_RESOURCE);
328                 assignment2.setIssuer("");
329                 AttributeValueType AttributeValue = new AttributeValueType();
330                 AttributeValue.setDataType(URI_DATATYPE);
331
332                 String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
333
334                 AttributeValue.getContent().add(content);
335                 assignment2.setExpression(new ObjectFactory()
336                                 .createAttributeValue(AttributeValue));
337                 advice.getAttributeAssignmentExpression().add(assignment2);
338
339                 // Policy Name Assignment
340                 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
341                 assignment3.setAttributeId("PolicyName");
342                 assignment3.setCategory(CATEGORY_RESOURCE);
343                 assignment3.setIssuer("");
344                 AttributeValueType attributeValue3 = new AttributeValueType();
345                 attributeValue3.setDataType(STRING_DATATYPE);
346                 fileName = FilenameUtils.removeExtension(fileName);
347                 fileName = fileName + ".xml";
348                 System.out.println(fileName);
349                 String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
350                                 fileName.length());
351                 if ((name == null) || (name.equals(""))) {
352                         name = fileName.substring(fileName.lastIndexOf("/") + 1,
353                                         fileName.length());
354                 }
355                 System.out.println(name);
356                 attributeValue3.getContent().add(name);
357                 assignment3.setExpression(new ObjectFactory()
358                                 .createAttributeValue(attributeValue3));
359                 advice.getAttributeAssignmentExpression().add(assignment3);
360
361                 // Version Number Assignment
362                 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
363                 assignment4.setAttributeId("VersionNumber");
364                 assignment4.setCategory(CATEGORY_RESOURCE);
365                 assignment4.setIssuer("");
366                 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
367                 configNameAttributeValue4.setDataType(STRING_DATATYPE);
368                 configNameAttributeValue4.getContent().add(Integer.toString(version));
369                 assignment4.setExpression(new ObjectFactory()
370                                 .createAttributeValue(configNameAttributeValue4));
371                 advice.getAttributeAssignmentExpression().add(assignment4);
372
373                 // Ecomp Name Assignment
374                 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
375                 assignment5.setAttributeId("matching:" + ECOMPID);
376                 assignment5.setCategory(CATEGORY_RESOURCE);
377                 assignment5.setIssuer("");
378                 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
379                 configNameAttributeValue5.setDataType(STRING_DATATYPE);
380                 configNameAttributeValue5.getContent().add(policyAdapter.getEcompName());
381                 assignment5.setExpression(new ObjectFactory()
382                                 .createAttributeValue(configNameAttributeValue5));
383                 advice.getAttributeAssignmentExpression().add(assignment5);
384                 
385                 
386                 //Config Name Assignment
387                 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
388                 assignment6.setAttributeId("matching:" + CONFIGID);
389                 assignment6.setCategory(CATEGORY_RESOURCE);
390                 assignment6.setIssuer("");
391                 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
392                 configNameAttributeValue6.setDataType(STRING_DATATYPE);
393                 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
394                 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
395                 advice.getAttributeAssignmentExpression().add(assignment6);
396                 
397         // Adding Controller Information. 
398         if(policyAdapter.getBrmsController()!=null){
399             BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
400             advice.getAttributeAssignmentExpression().add(
401                     createResponseAttributes("controller:"+ policyAdapter.getBrmsController(), 
402                                 brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController()));
403         }
404         
405         // Adding Dependencies. 
406         if(policyAdapter.getBrmsDependency()!=null){
407             BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
408             ArrayList<String> dependencies = new ArrayList<>();
409             StringBuilder key = new StringBuilder();
410             for(String dependencyName: policyAdapter.getBrmsDependency()){
411                 dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
412                 key.append(dependencyName + ",");
413             }
414             advice.getAttributeAssignmentExpression().add(
415                         createResponseAttributes("dependencies:"+key.toString(), dependencies.toString()));
416         }
417         
418         // Dynamic Field Config Attributes. 
419                 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
420                 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
421                         advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField)));
422                 }
423                 
424                 //Risk Attributes
425                 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
426                 assignment8.setAttributeId("RiskType");
427                 assignment8.setCategory(CATEGORY_RESOURCE);
428                 assignment8.setIssuer("");
429
430                 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
431                 configNameAttributeValue8.setDataType(STRING_DATATYPE);
432                 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
433                 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
434
435                 advice.getAttributeAssignmentExpression().add(assignment8);
436                 
437                 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
438                 assignment9.setAttributeId("RiskLevel");
439                 assignment9.setCategory(CATEGORY_RESOURCE);
440                 assignment9.setIssuer("");
441
442                 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
443                 configNameAttributeValue9.setDataType(STRING_DATATYPE);
444                 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
445                 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
446
447                 advice.getAttributeAssignmentExpression().add(assignment9);     
448
449                 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
450                 assignment10.setAttributeId("guard");
451                 assignment10.setCategory(CATEGORY_RESOURCE);
452                 assignment10.setIssuer("");
453
454                 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
455                 configNameAttributeValue10.setDataType(STRING_DATATYPE);
456                 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
457                 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
458
459                 advice.getAttributeAssignmentExpression().add(assignment10);
460
461                 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
462                 assignment11.setAttributeId("TTLDate");
463                 assignment11.setCategory(CATEGORY_RESOURCE);
464                 assignment11.setIssuer("");
465
466                 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
467                 configNameAttributeValue11.setDataType(STRING_DATATYPE);
468                 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
469                 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
470
471                 advice.getAttributeAssignmentExpression().add(assignment11);
472
473                 advices.getAdviceExpression().add(advice);
474                 return advices;
475         }
476
477         @Override
478         public Object getCorrectPolicyDataObject() {
479                 return policyAdapter.getData();
480         }
481         
482     private AttributeAssignmentExpressionType  createResponseAttributes(String key, String value){
483         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
484         assignment7.setAttributeId(key);
485         assignment7.setCategory(CATEGORY_RESOURCE);
486         assignment7.setIssuer("");
487         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
488         configNameAttributeValue7.setDataType(STRING_DATATYPE);
489         configNameAttributeValue7.getContent().add(value);
490         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
491         return assignment7;
492     }
493 }