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 private static final String EMPTY_STRING = "";
65 public CreateBrmsRawPolicy() {
69 public CreateBrmsRawPolicy(PolicyRestAdapter policyAdapter) {
70 this.policyAdapter = policyAdapter;
71 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
75 // Saving the Configurations file at server location for CreateBrmsRawPolicy policy.
76 protected void saveConfigurations(String policyName, String jsonBody) {
78 if (policyName.endsWith(".xml")) {
79 policyName = policyName.substring(0,
80 policyName.lastIndexOf(".xml"));
82 try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) {
83 out.println(jsonBody);
84 } catch (Exception e) {
85 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy",
86 "Exception saving configurations file");
90 // Utility to read json data from the existing file to a string
91 static String readFile(String path, Charset encoding) throws IOException {
93 byte[] encoded = Files.readAllBytes(Paths.get(path));
94 return new String(encoded, encoding);
98 // Here we are adding the extension for the configurations file based on the
99 // config type selection for saving.
100 private String getConfigFile(String filename) {
101 filename = FilenameUtils.removeExtension(filename);
102 if (filename.endsWith(".txt")) {
103 filename = filename.substring(0, filename.length() - 3);
106 filename = filename + ".txt";
110 // Validations for Config form
111 public boolean validateConfigForm() {
113 // Validating mandatory Fields.
120 public Map<String, String> savePolicies() throws PAPException {
122 Map<String, String> successMap = new HashMap<>();
123 if (isPolicyExists()) {
124 successMap.put("EXISTS", "This Policy already exist on the PAP");
128 if (!isPreparedToSave()) {
131 // Until here we prepared the data and here calling the method to create
133 Path newPolicyPath = null;
134 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
136 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
137 if (successMap == null) {
138 successMap = new HashMap<>();
139 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
140 successMap.put("error", "DB UPDATE");
146 // This is the method for preparing the policy for saving. We have broken it
148 // separately because the fully configured policy is used for multiple
151 public boolean prepareToSave() {
153 if (isPreparedToSave()) {
154 // we have already done this
159 String policyID = policyAdapter.getPolicyID();
160 version = policyAdapter.getHighestVersion();
162 // Create the Instance for pojo, PolicyType object is used in
164 if ("Config".equals(policyAdapter.getPolicyType())) {
165 PolicyType policyConfig = new PolicyType();
167 policyConfig.setVersion(Integer.toString(version));
168 policyConfig.setPolicyId(policyID);
169 policyConfig.setTarget(new TargetType());
170 policyAdapter.setData(policyConfig);
173 policyName = policyAdapter.getNewFileName();
175 if (policyAdapter.getData() != null) {
176 String configBody = policyAdapter.getConfigBodyData();
177 saveConfigurations(policyName, configBody);
179 // Make sure the filename ends with an extension
180 if (!policyName.endsWith(".xml")) {
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);
193 if (EMPTY_STRING.equals(name)) {
194 name = fileName.substring(fileName.lastIndexOf("/") + 1);
196 allOfOne.getMatch().add(createMatch("PolicyName", name));
199 AllOfType allOf = new AllOfType();
201 // Match for ONAPName
202 allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName()));
203 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
204 // Match for riskType
205 allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
206 // Match for riskLevel
207 allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
208 // Match for riskguard
209 allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
211 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
212 AnyOfType anyOf = new AnyOfType();
213 anyOf.getAllOf().add(allOfOne);
214 anyOf.getAllOf().add(allOf);
216 TargetType target = new TargetType();
217 target.getAnyOf().add(anyOf);
219 // Adding the target to the policy element
220 configPolicy.setTarget(target);
222 RuleType rule = new RuleType();
223 rule.setRuleId(policyAdapter.getRuleID());
225 rule.setEffect(EffectType.PERMIT);
227 // Create Target in Rule
228 AllOfType allOfInRule = new AllOfType();
230 // Creating match for ACCESS in rule target
231 MatchType accessMatch = new MatchType();
232 AttributeValueType accessAttributeValue = new AttributeValueType();
233 accessAttributeValue.setDataType(STRING_DATATYPE);
234 accessAttributeValue.getContent().add("ACCESS");
235 accessMatch.setAttributeValue(accessAttributeValue);
236 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
237 URI accessURI = null;
239 accessURI = new URI(ACTION_ID);
240 } catch (URISyntaxException e) {
241 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy",
242 "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",
265 "Exception creating Config URI");
268 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
269 configAttributeDesignator.setDataType(STRING_DATATYPE);
270 configAttributeDesignator.setAttributeId(new IdentifierImpl(
271 configURI).stringValue());
272 configMatch.setAttributeDesignator(configAttributeDesignator);
273 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
275 allOfInRule.getMatch().add(accessMatch);
276 allOfInRule.getMatch().add(configMatch);
278 AnyOfType anyOfInRule = new AnyOfType();
279 anyOfInRule.getAllOf().add(allOfInRule);
281 TargetType targetInRule = new TargetType();
282 targetInRule.getAnyOf().add(anyOfInRule);
284 rule.setTarget(targetInRule);
285 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
288 .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
290 policyAdapter.setPolicyData(configPolicy);
293 PolicyLogger.error("Unsupported data object."
294 + policyAdapter.getData().getClass().getCanonicalName());
296 setPreparedToSave(true);
300 // Data required for Advice part is setting here.
301 private AdviceExpressionsType getAdviceExpressions(int version,
304 // Policy Config ID Assignment
305 AdviceExpressionsType advices = new AdviceExpressionsType();
306 AdviceExpressionType advice = new AdviceExpressionType();
307 advice.setAdviceId("BRMSRAWID");
308 advice.setAppliesTo(EffectType.PERMIT);
310 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
311 assignment1.setAttributeId("type");
312 assignment1.setCategory(CATEGORY_RESOURCE);
313 assignment1.setIssuer(EMPTY_STRING);
314 AttributeValueType configNameAttributeValue = new AttributeValueType();
315 configNameAttributeValue.setDataType(STRING_DATATYPE);
316 configNameAttributeValue.getContent().add("Configuration");
317 assignment1.setExpression(new ObjectFactory()
318 .createAttributeValue(configNameAttributeValue));
319 advice.getAttributeAssignmentExpression().add(assignment1);
321 // For Config file Url if configurations are provided.
323 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
324 assignment2.setAttributeId("URLID");
325 assignment2.setCategory(CATEGORY_RESOURCE);
326 assignment2.setIssuer(EMPTY_STRING);
327 AttributeValueType AttributeValue = new AttributeValueType();
328 AttributeValue.setDataType(URI_DATATYPE);
330 String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
332 AttributeValue.getContent().add(content);
333 assignment2.setExpression(new ObjectFactory()
334 .createAttributeValue(AttributeValue));
335 advice.getAttributeAssignmentExpression().add(assignment2);
337 // Policy Name Assignment
338 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
339 assignment3.setAttributeId("PolicyName");
340 assignment3.setCategory(CATEGORY_RESOURCE);
341 assignment3.setIssuer(EMPTY_STRING);
342 AttributeValueType attributeValue3 = new AttributeValueType();
343 attributeValue3.setDataType(STRING_DATATYPE);
344 fileName = FilenameUtils.removeExtension(fileName);
345 fileName = fileName + ".xml";
346 System.out.println(fileName);
347 String name = fileName.substring(fileName.lastIndexOf("\\") + 1);
348 if (EMPTY_STRING.equals(name)) {
349 name = fileName.substring(fileName.lastIndexOf("/") + 1);
351 System.out.println(name);
352 attributeValue3.getContent().add(name);
353 assignment3.setExpression(new ObjectFactory()
354 .createAttributeValue(attributeValue3));
355 advice.getAttributeAssignmentExpression().add(assignment3);
357 // Version Number Assignment
358 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
359 assignment4.setAttributeId("VersionNumber");
360 assignment4.setCategory(CATEGORY_RESOURCE);
361 assignment4.setIssuer(EMPTY_STRING);
362 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
363 configNameAttributeValue4.setDataType(STRING_DATATYPE);
364 configNameAttributeValue4.getContent().add(Integer.toString(version));
365 assignment4.setExpression(new ObjectFactory()
366 .createAttributeValue(configNameAttributeValue4));
367 advice.getAttributeAssignmentExpression().add(assignment4);
369 // Onap Name Assignment
370 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
371 assignment5.setAttributeId("matching:" + ONAPID);
372 assignment5.setCategory(CATEGORY_RESOURCE);
373 assignment5.setIssuer(EMPTY_STRING);
374 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
375 configNameAttributeValue5.setDataType(STRING_DATATYPE);
376 configNameAttributeValue5.getContent().add(policyAdapter.getOnapName());
377 assignment5.setExpression(new ObjectFactory()
378 .createAttributeValue(configNameAttributeValue5));
379 advice.getAttributeAssignmentExpression().add(assignment5);
382 //Config Name Assignment
383 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
384 assignment6.setAttributeId("matching:" + CONFIGID);
385 assignment6.setCategory(CATEGORY_RESOURCE);
386 assignment6.setIssuer(EMPTY_STRING);
387 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
388 configNameAttributeValue6.setDataType(STRING_DATATYPE);
389 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
390 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
391 advice.getAttributeAssignmentExpression().add(assignment6);
393 // Adding Controller Information.
394 if (policyAdapter.getBrmsController() != null) {
395 BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
396 advice.getAttributeAssignmentExpression().add(
397 createResponseAttributes("controller:" + policyAdapter.getBrmsController(),
398 brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController())
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).append(",");
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 (Map.Entry<String, String> entry : dynamicFieldConfigAttributes.entrySet()) {
418 String keyField = entry.getKey();
419 advice.getAttributeAssignmentExpression()
420 .add(createResponseAttributes("key:" + keyField, entry.getValue()));
424 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
425 assignment8.setAttributeId("RiskType");
426 assignment8.setCategory(CATEGORY_RESOURCE);
427 assignment8.setIssuer(EMPTY_STRING);
429 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
430 configNameAttributeValue8.setDataType(STRING_DATATYPE);
431 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
432 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
434 advice.getAttributeAssignmentExpression().add(assignment8);
436 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
437 assignment9.setAttributeId("RiskLevel");
438 assignment9.setCategory(CATEGORY_RESOURCE);
439 assignment9.setIssuer(EMPTY_STRING);
441 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
442 configNameAttributeValue9.setDataType(STRING_DATATYPE);
443 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
444 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
446 advice.getAttributeAssignmentExpression().add(assignment9);
448 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
449 assignment10.setAttributeId("guard");
450 assignment10.setCategory(CATEGORY_RESOURCE);
451 assignment10.setIssuer(EMPTY_STRING);
453 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
454 configNameAttributeValue10.setDataType(STRING_DATATYPE);
455 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
456 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
458 advice.getAttributeAssignmentExpression().add(assignment10);
460 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
461 assignment11.setAttributeId("TTLDate");
462 assignment11.setCategory(CATEGORY_RESOURCE);
463 assignment11.setIssuer(EMPTY_STRING);
465 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
466 configNameAttributeValue11.setDataType(STRING_DATATYPE);
467 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
468 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
470 advice.getAttributeAssignmentExpression().add(assignment11);
472 advices.getAdviceExpression().add(advice);
477 public Object getCorrectPolicyDataObject() {
478 return policyAdapter.getData();
481 private AttributeAssignmentExpressionType createResponseAttributes(String key, String value) {
482 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
483 assignment7.setAttributeId(key);
484 assignment7.setCategory(CATEGORY_RESOURCE);
485 assignment7.setIssuer(EMPTY_STRING);
486 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
487 configNameAttributeValue7.setDataType(STRING_DATATYPE);
488 configNameAttributeValue7.getContent().add(value);
489 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));