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 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt");
81 out.println(jsonBody);
84 } catch (Exception e) {
85 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy", "Exception saving configurations file");
89 // Utility to read json data from the existing file to a string
90 static String readFile(String path, Charset encoding) throws IOException {
92 byte[] encoded = Files.readAllBytes(Paths.get(path));
93 return new String(encoded, encoding);
97 // Here we are adding the extension for the configurations file based on the
98 // config type selection for saving.
99 private String getConfigFile(String filename) {
100 filename = FilenameUtils.removeExtension(filename);
101 if (filename.endsWith(".txt")) {
102 filename = filename.substring(0, filename.length() - 3);
105 filename = filename + ".txt";
109 // Validations for Config form
110 public boolean validateConfigForm() {
112 // Validating mandatory Fields.
119 public Map<String, String> savePolicies() throws PAPException {
121 Map<String, String> successMap = new HashMap<>();
122 if(isPolicyExists()){
123 successMap.put("EXISTS", "This Policy already exist on the PAP");
127 if (!isPreparedToSave()) {
130 // Until here we prepared the data and here calling the method to create
132 Path newPolicyPath = null;
133 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
135 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
136 if (successMap == null) {
137 successMap = new HashMap<>();
138 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
139 successMap.put("error", "DB UPDATE");
145 // This is the method for preparing the policy for saving. We have broken it
147 // separately because the fully configured policy is used for multiple
150 public boolean prepareToSave() throws PAPException {
152 if (isPreparedToSave()) {
153 // we have already done this
158 String policyID = policyAdapter.getPolicyID();
159 version = policyAdapter.getHighestVersion();
161 // Create the Instance for pojo, PolicyType object is used in
163 if (policyAdapter.getPolicyType().equals("Config")) {
164 PolicyType policyConfig = new PolicyType();
166 policyConfig.setVersion(Integer.toString(version));
167 policyConfig.setPolicyId(policyID);
168 policyConfig.setTarget(new TargetType());
169 policyAdapter.setData(policyConfig);
172 policyName = policyAdapter.getNewFileName();
174 if (policyAdapter.getData() != null) {
175 //String jsonBody = policyAdapter.getJsonBody();
176 String configBody=policyAdapter.getConfigBodyData();
177 saveConfigurations(policyName, configBody);
179 // Make sure the filename ends with an extension
180 if (policyName.endsWith(".xml") == false) {
181 policyName = policyName + ".xml";
184 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
186 configPolicy.setDescription(policyAdapter.getPolicyDescription());
188 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
190 AllOfType allOfOne = new AllOfType();
191 String fileName = policyAdapter.getNewFileName();
192 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
193 if ((name == null) || (name.equals(""))) {
194 name = fileName.substring(fileName.lastIndexOf("/") + 1,
197 allOfOne.getMatch().add(createMatch("PolicyName", name));
200 AllOfType allOf = new AllOfType();
202 // Match for ONAPName
203 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
204 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
205 // Match for riskType
206 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
207 // Match for riskLevel
208 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
209 // Match for riskguard
210 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
212 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
213 AnyOfType anyOf = new AnyOfType();
214 anyOf.getAllOf().add(allOfOne);
215 anyOf.getAllOf().add(allOf);
217 TargetType target = new TargetType();
218 ((TargetType) target).getAnyOf().add(anyOf);
220 // Adding the target to the policy element
221 configPolicy.setTarget((TargetType) target);
223 RuleType rule = new RuleType();
224 rule.setRuleId(policyAdapter.getRuleID());
226 rule.setEffect(EffectType.PERMIT);
228 // Create Target in Rule
229 AllOfType allOfInRule = new AllOfType();
231 // Creating match for ACCESS in rule target
232 MatchType accessMatch = new MatchType();
233 AttributeValueType accessAttributeValue = new AttributeValueType();
234 accessAttributeValue.setDataType(STRING_DATATYPE);
235 accessAttributeValue.getContent().add("ACCESS");
236 accessMatch.setAttributeValue(accessAttributeValue);
237 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
238 URI accessURI = null;
240 accessURI = new URI(ACTION_ID);
241 } catch (URISyntaxException e) {
242 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating ACCESS URI");
244 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
245 accessAttributeDesignator.setDataType(STRING_DATATYPE);
246 accessAttributeDesignator.setAttributeId(new IdentifierImpl(
247 accessURI).stringValue());
248 accessMatch.setAttributeDesignator(accessAttributeDesignator);
249 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
251 // Creating Config Match in rule Target
252 MatchType configMatch = new MatchType();
253 AttributeValueType configAttributeValue = new AttributeValueType();
254 configAttributeValue.setDataType(STRING_DATATYPE);
256 configAttributeValue.getContent().add("Config");
258 configMatch.setAttributeValue(configAttributeValue);
259 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
260 URI configURI = null;
262 configURI = new URI(RESOURCE_ID);
263 } catch (URISyntaxException e) {
264 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating Config URI");
267 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
268 configAttributeDesignator.setDataType(STRING_DATATYPE);
269 configAttributeDesignator.setAttributeId(new IdentifierImpl(
270 configURI).stringValue());
271 configMatch.setAttributeDesignator(configAttributeDesignator);
272 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
274 allOfInRule.getMatch().add(accessMatch);
275 allOfInRule.getMatch().add(configMatch);
277 AnyOfType anyOfInRule = new AnyOfType();
278 anyOfInRule.getAllOf().add(allOfInRule);
280 TargetType targetInRule = new TargetType();
281 targetInRule.getAnyOf().add(anyOfInRule);
283 rule.setTarget(targetInRule);
284 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
287 .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
289 policyAdapter.setPolicyData(configPolicy);
292 PolicyLogger.error("Unsupported data object."
293 + policyAdapter.getData().getClass().getCanonicalName());
295 setPreparedToSave(true);
299 // Data required for Advice part is setting here.
300 private AdviceExpressionsType getAdviceExpressions(int version,
303 // Policy Config ID Assignment
304 AdviceExpressionsType advices = new AdviceExpressionsType();
305 AdviceExpressionType advice = new AdviceExpressionType();
306 advice.setAdviceId("BRMSRAWID");
307 advice.setAppliesTo(EffectType.PERMIT);
309 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
310 assignment1.setAttributeId("type");
311 assignment1.setCategory(CATEGORY_RESOURCE);
312 assignment1.setIssuer("");
313 AttributeValueType configNameAttributeValue = new AttributeValueType();
314 configNameAttributeValue.setDataType(STRING_DATATYPE);
315 configNameAttributeValue.getContent().add("Configuration");
316 assignment1.setExpression(new ObjectFactory()
317 .createAttributeValue(configNameAttributeValue));
318 advice.getAttributeAssignmentExpression().add(assignment1);
320 // For Config file Url if configurations are provided.
322 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
323 assignment2.setAttributeId("URLID");
324 assignment2.setCategory(CATEGORY_RESOURCE);
325 assignment2.setIssuer("");
326 AttributeValueType AttributeValue = new AttributeValueType();
327 AttributeValue.setDataType(URI_DATATYPE);
329 String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
331 AttributeValue.getContent().add(content);
332 assignment2.setExpression(new ObjectFactory()
333 .createAttributeValue(AttributeValue));
334 advice.getAttributeAssignmentExpression().add(assignment2);
336 // Policy Name Assignment
337 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
338 assignment3.setAttributeId("PolicyName");
339 assignment3.setCategory(CATEGORY_RESOURCE);
340 assignment3.setIssuer("");
341 AttributeValueType attributeValue3 = new AttributeValueType();
342 attributeValue3.setDataType(STRING_DATATYPE);
343 fileName = FilenameUtils.removeExtension(fileName);
344 fileName = fileName + ".xml";
345 System.out.println(fileName);
346 String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
348 if ((name == null) || (name.equals(""))) {
349 name = fileName.substring(fileName.lastIndexOf("/") + 1,
352 System.out.println(name);
353 attributeValue3.getContent().add(name);
354 assignment3.setExpression(new ObjectFactory()
355 .createAttributeValue(attributeValue3));
356 advice.getAttributeAssignmentExpression().add(assignment3);
358 // Version Number Assignment
359 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
360 assignment4.setAttributeId("VersionNumber");
361 assignment4.setCategory(CATEGORY_RESOURCE);
362 assignment4.setIssuer("");
363 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
364 configNameAttributeValue4.setDataType(STRING_DATATYPE);
365 configNameAttributeValue4.getContent().add(Integer.toString(version));
366 assignment4.setExpression(new ObjectFactory()
367 .createAttributeValue(configNameAttributeValue4));
368 advice.getAttributeAssignmentExpression().add(assignment4);
370 // Onap Name Assignment
371 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
372 assignment5.setAttributeId("matching:" + ONAPID);
373 assignment5.setCategory(CATEGORY_RESOURCE);
374 assignment5.setIssuer("");
375 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
376 configNameAttributeValue5.setDataType(STRING_DATATYPE);
377 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
378 assignment5.setExpression(new ObjectFactory()
379 .createAttributeValue(configNameAttributeValue5));
380 advice.getAttributeAssignmentExpression().add(assignment5);
383 //Config Name Assignment
384 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
385 assignment6.setAttributeId("matching:" + CONFIGID);
386 assignment6.setCategory(CATEGORY_RESOURCE);
387 assignment6.setIssuer("");
388 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
389 configNameAttributeValue6.setDataType(STRING_DATATYPE);
390 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
391 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
392 advice.getAttributeAssignmentExpression().add(assignment6);
394 // Adding Controller Information.
395 if(policyAdapter.getBrmsController()!=null){
396 BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
397 advice.getAttributeAssignmentExpression().add(
398 createResponseAttributes("controller:"+ policyAdapter.getBrmsController(),
399 brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController()));
402 // Adding Dependencies.
403 if(policyAdapter.getBrmsDependency()!=null){
404 BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
405 ArrayList<String> dependencies = new ArrayList<>();
406 StringBuilder key = new StringBuilder();
407 for(String dependencyName: policyAdapter.getBrmsDependency()){
408 dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
409 key.append(dependencyName + ",");
411 advice.getAttributeAssignmentExpression().add(
412 createResponseAttributes("dependencies:"+key.toString(), dependencies.toString()));
415 // Dynamic Field Config Attributes.
416 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
417 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
418 advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField)));
422 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
423 assignment8.setAttributeId("RiskType");
424 assignment8.setCategory(CATEGORY_RESOURCE);
425 assignment8.setIssuer("");
427 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
428 configNameAttributeValue8.setDataType(STRING_DATATYPE);
429 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
430 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
432 advice.getAttributeAssignmentExpression().add(assignment8);
434 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
435 assignment9.setAttributeId("RiskLevel");
436 assignment9.setCategory(CATEGORY_RESOURCE);
437 assignment9.setIssuer("");
439 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
440 configNameAttributeValue9.setDataType(STRING_DATATYPE);
441 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
442 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
444 advice.getAttributeAssignmentExpression().add(assignment9);
446 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
447 assignment10.setAttributeId("guard");
448 assignment10.setCategory(CATEGORY_RESOURCE);
449 assignment10.setIssuer("");
451 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
452 configNameAttributeValue10.setDataType(STRING_DATATYPE);
453 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
454 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
456 advice.getAttributeAssignmentExpression().add(assignment10);
458 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
459 assignment11.setAttributeId("TTLDate");
460 assignment11.setCategory(CATEGORY_RESOURCE);
461 assignment11.setIssuer("");
463 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
464 configNameAttributeValue11.setDataType(STRING_DATATYPE);
465 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
466 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
468 advice.getAttributeAssignmentExpression().add(assignment11);
470 advices.getAdviceExpression().add(advice);
475 public Object getCorrectPolicyDataObject() {
476 return policyAdapter.getData();
479 private AttributeAssignmentExpressionType createResponseAttributes(String key, String value){
480 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
481 assignment7.setAttributeId(key);
482 assignment7.setCategory(CATEGORY_RESOURCE);
483 assignment7.setIssuer("");
484 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
485 configNameAttributeValue7.setDataType(STRING_DATATYPE);
486 configNameAttributeValue7.getContent().add(value);
487 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));