2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.policy.pap.xacml.rest.components;
25 import java.io.IOException;
26 import java.io.PrintWriter;
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;
37 import org.apache.commons.io.FilenameUtils;
38 import org.onap.policy.common.logging.eelf.MessageCodes;
39 import org.onap.policy.common.logging.eelf.PolicyLogger;
40 import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController;
41 import org.onap.policy.rest.adapter.PolicyRestAdapter;
43 import com.att.research.xacml.api.pap.PAPException;
44 import com.att.research.xacml.std.IdentifierImpl;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
61 public class CreateBrmsRawPolicy extends Policy {
63 public CreateBrmsRawPolicy() {
67 public CreateBrmsRawPolicy(PolicyRestAdapter policyAdapter) {
68 this.policyAdapter = policyAdapter;
69 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
73 // Saving the Configurations file at server location for CreateBrmsRawPolicy policy.
74 protected void saveConfigurations(String policyName, String jsonBody) {
76 if (policyName.endsWith(".xml")) {
77 policyName = policyName.substring(0,
78 policyName.lastIndexOf(".xml"));
80 try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")){
81 out.println(jsonBody);
82 } catch (Exception e) {
83 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy", "Exception saving configurations file");
87 // Utility to read json data from the existing file to a string
88 static String readFile(String path, Charset encoding) throws IOException {
90 byte[] encoded = Files.readAllBytes(Paths.get(path));
91 return new String(encoded, encoding);
95 // Here we are adding the extension for the configurations file based on the
96 // config type selection for saving.
97 private String getConfigFile(String filename) {
98 filename = FilenameUtils.removeExtension(filename);
99 if (filename.endsWith(".txt")) {
100 filename = filename.substring(0, filename.length() - 3);
103 filename = filename + ".txt";
107 // Validations for Config form
108 public boolean validateConfigForm() {
110 // Validating mandatory Fields.
117 public Map<String, String> savePolicies() throws PAPException {
119 Map<String, String> successMap = new HashMap<>();
120 if(isPolicyExists()){
121 successMap.put("EXISTS", "This Policy already exist on the PAP");
125 if (!isPreparedToSave()) {
128 // Until here we prepared the data and here calling the method to create
130 Path newPolicyPath = null;
131 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
133 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
134 if (successMap == null) {
135 successMap = new HashMap<>();
136 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
137 successMap.put("error", "DB UPDATE");
143 // This is the method for preparing the policy for saving. We have broken it
145 // separately because the fully configured policy is used for multiple
148 public boolean prepareToSave() throws PAPException {
150 if (isPreparedToSave()) {
151 // we have already done this
156 String policyID = policyAdapter.getPolicyID();
157 version = policyAdapter.getHighestVersion();
159 // Create the Instance for pojo, PolicyType object is used in
161 if (policyAdapter.getPolicyType().equals("Config")) {
162 PolicyType policyConfig = new PolicyType();
164 policyConfig.setVersion(Integer.toString(version));
165 policyConfig.setPolicyId(policyID);
166 policyConfig.setTarget(new TargetType());
167 policyAdapter.setData(policyConfig);
170 policyName = policyAdapter.getNewFileName();
172 if (policyAdapter.getData() != null) {
173 //String jsonBody = policyAdapter.getJsonBody();
174 String configBody=policyAdapter.getConfigBodyData();
175 saveConfigurations(policyName, configBody);
177 // Make sure the filename ends with an extension
178 if (policyName.endsWith(".xml") == false) {
179 policyName = policyName + ".xml";
182 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
184 configPolicy.setDescription(policyAdapter.getPolicyDescription());
186 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
188 AllOfType allOfOne = new AllOfType();
189 String fileName = policyAdapter.getNewFileName();
190 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
191 if ((name == null) || (name.equals(""))) {
192 name = fileName.substring(fileName.lastIndexOf("/") + 1,
195 allOfOne.getMatch().add(createMatch("PolicyName", name));
198 AllOfType allOf = new AllOfType();
200 // Match for ONAPName
201 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
202 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
203 // Match for riskType
204 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
205 // Match for riskLevel
206 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
207 // Match for riskguard
208 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
210 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
211 AnyOfType anyOf = new AnyOfType();
212 anyOf.getAllOf().add(allOfOne);
213 anyOf.getAllOf().add(allOf);
215 TargetType target = new TargetType();
216 ((TargetType) target).getAnyOf().add(anyOf);
218 // Adding the target to the policy element
219 configPolicy.setTarget((TargetType) target);
221 RuleType rule = new RuleType();
222 rule.setRuleId(policyAdapter.getRuleID());
224 rule.setEffect(EffectType.PERMIT);
226 // Create Target in Rule
227 AllOfType allOfInRule = new AllOfType();
229 // Creating match for ACCESS in rule target
230 MatchType accessMatch = new MatchType();
231 AttributeValueType accessAttributeValue = new AttributeValueType();
232 accessAttributeValue.setDataType(STRING_DATATYPE);
233 accessAttributeValue.getContent().add("ACCESS");
234 accessMatch.setAttributeValue(accessAttributeValue);
235 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
236 URI accessURI = null;
238 accessURI = new URI(ACTION_ID);
239 } catch (URISyntaxException e) {
240 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating ACCESS URI");
242 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
243 accessAttributeDesignator.setDataType(STRING_DATATYPE);
244 accessAttributeDesignator.setAttributeId(new IdentifierImpl(
245 accessURI).stringValue());
246 accessMatch.setAttributeDesignator(accessAttributeDesignator);
247 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
249 // Creating Config Match in rule Target
250 MatchType configMatch = new MatchType();
251 AttributeValueType configAttributeValue = new AttributeValueType();
252 configAttributeValue.setDataType(STRING_DATATYPE);
254 configAttributeValue.getContent().add("Config");
256 configMatch.setAttributeValue(configAttributeValue);
257 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
258 URI configURI = null;
260 configURI = new URI(RESOURCE_ID);
261 } catch (URISyntaxException e) {
262 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating Config URI");
265 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
266 configAttributeDesignator.setDataType(STRING_DATATYPE);
267 configAttributeDesignator.setAttributeId(new IdentifierImpl(
268 configURI).stringValue());
269 configMatch.setAttributeDesignator(configAttributeDesignator);
270 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
272 allOfInRule.getMatch().add(accessMatch);
273 allOfInRule.getMatch().add(configMatch);
275 AnyOfType anyOfInRule = new AnyOfType();
276 anyOfInRule.getAllOf().add(allOfInRule);
278 TargetType targetInRule = new TargetType();
279 targetInRule.getAnyOf().add(anyOfInRule);
281 rule.setTarget(targetInRule);
282 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
285 .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
287 policyAdapter.setPolicyData(configPolicy);
290 PolicyLogger.error("Unsupported data object."
291 + policyAdapter.getData().getClass().getCanonicalName());
293 setPreparedToSave(true);
297 // Data required for Advice part is setting here.
298 private AdviceExpressionsType getAdviceExpressions(int version,
301 // Policy Config ID Assignment
302 AdviceExpressionsType advices = new AdviceExpressionsType();
303 AdviceExpressionType advice = new AdviceExpressionType();
304 advice.setAdviceId("BRMSRAWID");
305 advice.setAppliesTo(EffectType.PERMIT);
307 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
308 assignment1.setAttributeId("type");
309 assignment1.setCategory(CATEGORY_RESOURCE);
310 assignment1.setIssuer("");
311 AttributeValueType configNameAttributeValue = new AttributeValueType();
312 configNameAttributeValue.setDataType(STRING_DATATYPE);
313 configNameAttributeValue.getContent().add("Configuration");
314 assignment1.setExpression(new ObjectFactory()
315 .createAttributeValue(configNameAttributeValue));
316 advice.getAttributeAssignmentExpression().add(assignment1);
318 // For Config file Url if configurations are provided.
320 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
321 assignment2.setAttributeId("URLID");
322 assignment2.setCategory(CATEGORY_RESOURCE);
323 assignment2.setIssuer("");
324 AttributeValueType AttributeValue = new AttributeValueType();
325 AttributeValue.setDataType(URI_DATATYPE);
327 String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
329 AttributeValue.getContent().add(content);
330 assignment2.setExpression(new ObjectFactory()
331 .createAttributeValue(AttributeValue));
332 advice.getAttributeAssignmentExpression().add(assignment2);
334 // Policy Name Assignment
335 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
336 assignment3.setAttributeId("PolicyName");
337 assignment3.setCategory(CATEGORY_RESOURCE);
338 assignment3.setIssuer("");
339 AttributeValueType attributeValue3 = new AttributeValueType();
340 attributeValue3.setDataType(STRING_DATATYPE);
341 fileName = FilenameUtils.removeExtension(fileName);
342 fileName = fileName + ".xml";
343 System.out.println(fileName);
344 String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
346 if ((name == null) || (name.equals(""))) {
347 name = fileName.substring(fileName.lastIndexOf("/") + 1,
350 System.out.println(name);
351 attributeValue3.getContent().add(name);
352 assignment3.setExpression(new ObjectFactory()
353 .createAttributeValue(attributeValue3));
354 advice.getAttributeAssignmentExpression().add(assignment3);
356 // Version Number Assignment
357 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
358 assignment4.setAttributeId("VersionNumber");
359 assignment4.setCategory(CATEGORY_RESOURCE);
360 assignment4.setIssuer("");
361 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
362 configNameAttributeValue4.setDataType(STRING_DATATYPE);
363 configNameAttributeValue4.getContent().add(Integer.toString(version));
364 assignment4.setExpression(new ObjectFactory()
365 .createAttributeValue(configNameAttributeValue4));
366 advice.getAttributeAssignmentExpression().add(assignment4);
368 // Onap Name Assignment
369 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
370 assignment5.setAttributeId("matching:" + ONAPID);
371 assignment5.setCategory(CATEGORY_RESOURCE);
372 assignment5.setIssuer("");
373 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
374 configNameAttributeValue5.setDataType(STRING_DATATYPE);
375 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
376 assignment5.setExpression(new ObjectFactory()
377 .createAttributeValue(configNameAttributeValue5));
378 advice.getAttributeAssignmentExpression().add(assignment5);
381 //Config Name Assignment
382 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
383 assignment6.setAttributeId("matching:" + CONFIGID);
384 assignment6.setCategory(CATEGORY_RESOURCE);
385 assignment6.setIssuer("");
386 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
387 configNameAttributeValue6.setDataType(STRING_DATATYPE);
388 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
389 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
390 advice.getAttributeAssignmentExpression().add(assignment6);
392 // Adding Controller Information.
393 if(policyAdapter.getBrmsController()!=null){
394 BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
395 advice.getAttributeAssignmentExpression().add(
396 createResponseAttributes("controller:"+ policyAdapter.getBrmsController(),
397 brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController()));
400 // Adding Dependencies.
401 if(policyAdapter.getBrmsDependency()!=null){
402 BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
403 ArrayList<String> dependencies = new ArrayList<>();
404 StringBuilder key = new StringBuilder();
405 for(String dependencyName: policyAdapter.getBrmsDependency()){
406 dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
407 key.append(dependencyName + ",");
409 advice.getAttributeAssignmentExpression().add(
410 createResponseAttributes("dependencies:"+key.toString(), dependencies.toString()));
413 // Dynamic Field Config Attributes.
414 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
415 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
416 advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField)));
420 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
421 assignment8.setAttributeId("RiskType");
422 assignment8.setCategory(CATEGORY_RESOURCE);
423 assignment8.setIssuer("");
425 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
426 configNameAttributeValue8.setDataType(STRING_DATATYPE);
427 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
428 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
430 advice.getAttributeAssignmentExpression().add(assignment8);
432 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
433 assignment9.setAttributeId("RiskLevel");
434 assignment9.setCategory(CATEGORY_RESOURCE);
435 assignment9.setIssuer("");
437 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
438 configNameAttributeValue9.setDataType(STRING_DATATYPE);
439 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
440 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
442 advice.getAttributeAssignmentExpression().add(assignment9);
444 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
445 assignment10.setAttributeId("guard");
446 assignment10.setCategory(CATEGORY_RESOURCE);
447 assignment10.setIssuer("");
449 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
450 configNameAttributeValue10.setDataType(STRING_DATATYPE);
451 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
452 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
454 advice.getAttributeAssignmentExpression().add(assignment10);
456 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
457 assignment11.setAttributeId("TTLDate");
458 assignment11.setCategory(CATEGORY_RESOURCE);
459 assignment11.setIssuer("");
461 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
462 configNameAttributeValue11.setDataType(STRING_DATATYPE);
463 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
464 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
466 advice.getAttributeAssignmentExpression().add(assignment11);
468 advices.getAdviceExpression().add(advice);
473 public Object getCorrectPolicyDataObject() {
474 return policyAdapter.getData();
477 private AttributeAssignmentExpressionType createResponseAttributes(String key, String value){
478 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
479 assignment7.setAttributeId(key);
480 assignment7.setCategory(CATEGORY_RESOURCE);
481 assignment7.setIssuer("");
482 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
483 configNameAttributeValue7.setDataType(STRING_DATATYPE);
484 configNameAttributeValue7.getContent().add(value);
485 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));