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.std.IdentifierImpl;
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;
60 public class CreateBrmsRawPolicy extends Policy {
62 public CreateBrmsRawPolicy() {
66 public CreateBrmsRawPolicy(PolicyRestAdapter policyAdapter) {
67 this.policyAdapter = policyAdapter;
68 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
72 // Saving the Configurations file at server location for CreateBrmsRawPolicy policy.
73 protected void saveConfigurations(String policyName, String jsonBody) {
75 if (policyName.endsWith(".xml")) {
76 policyName = policyName.substring(0,
77 policyName.lastIndexOf(".xml"));
79 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt");
80 out.println(jsonBody);
83 } catch (Exception e) {
84 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsRawPolicy", "Exception saving configurations file");
88 // Utility to read json data from the existing file to a string
89 static String readFile(String path, Charset encoding) throws IOException {
91 byte[] encoded = Files.readAllBytes(Paths.get(path));
92 return new String(encoded, encoding);
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);
104 filename = filename + ".txt";
108 // Validations for Config form
109 public boolean validateConfigForm() {
111 // Validating mandatory Fields.
118 public Map<String, String> savePolicies() throws Exception {
120 Map<String, String> successMap = new HashMap<>();
121 if(isPolicyExists()){
122 successMap.put("EXISTS", "This Policy already exist on the PAP");
126 if (!isPreparedToSave()) {
129 // Until here we prepared the data and here calling the method to create
131 Path newPolicyPath = null;
132 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
134 successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject());
135 if (successMap == null) {
136 successMap = new HashMap<>();
137 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
138 successMap.put("error", "DB UPDATE");
144 // This is the method for preparing the policy for saving. We have broken it
146 // separately because the fully configured policy is used for multiple
149 public boolean prepareToSave() throws Exception {
151 if (isPreparedToSave()) {
152 // we have already done this
157 String policyID = policyAdapter.getPolicyID();
158 version = policyAdapter.getHighestVersion();
160 // Create the Instance for pojo, PolicyType object is used in
162 if (policyAdapter.getPolicyType().equals("Config")) {
163 PolicyType policyConfig = new PolicyType();
165 policyConfig.setVersion(Integer.toString(version));
166 policyConfig.setPolicyId(policyID);
167 policyConfig.setTarget(new TargetType());
168 policyAdapter.setData(policyConfig);
171 policyName = policyAdapter.getNewFileName();
173 if (policyAdapter.getData() != null) {
174 //String jsonBody = policyAdapter.getJsonBody();
175 String configBody=policyAdapter.getConfigBodyData();
176 saveConfigurations(policyName, configBody);
178 // Make sure the filename ends with an extension
179 if (policyName.endsWith(".xml") == false) {
180 policyName = policyName + ".xml";
183 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
185 configPolicy.setDescription(policyAdapter.getPolicyDescription());
187 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
189 AllOfType allOfOne = new AllOfType();
190 String fileName = policyAdapter.getNewFileName();
191 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
192 if ((name == null) || (name.equals(""))) {
193 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 ((TargetType) target).getAnyOf().add(anyOf);
219 // Adding the target to the policy element
220 configPolicy.setTarget((TargetType) 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", "Exception creating ACCESS URI");
243 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
244 accessAttributeDesignator.setDataType(STRING_DATATYPE);
245 accessAttributeDesignator.setAttributeId(new IdentifierImpl(
246 accessURI).stringValue());
247 accessMatch.setAttributeDesignator(accessAttributeDesignator);
248 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
250 // Creating Config Match in rule Target
251 MatchType configMatch = new MatchType();
252 AttributeValueType configAttributeValue = new AttributeValueType();
253 configAttributeValue.setDataType(STRING_DATATYPE);
255 configAttributeValue.getContent().add("Config");
257 configMatch.setAttributeValue(configAttributeValue);
258 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
259 URI configURI = null;
261 configURI = new URI(RESOURCE_ID);
262 } catch (URISyntaxException e) {
263 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating Config URI");
266 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
267 configAttributeDesignator.setDataType(STRING_DATATYPE);
268 configAttributeDesignator.setAttributeId(new IdentifierImpl(
269 configURI).stringValue());
270 configMatch.setAttributeDesignator(configAttributeDesignator);
271 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
273 allOfInRule.getMatch().add(accessMatch);
274 allOfInRule.getMatch().add(configMatch);
276 AnyOfType anyOfInRule = new AnyOfType();
277 anyOfInRule.getAllOf().add(allOfInRule);
279 TargetType targetInRule = new TargetType();
280 targetInRule.getAnyOf().add(anyOfInRule);
282 rule.setTarget(targetInRule);
283 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
286 .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
288 policyAdapter.setPolicyData(configPolicy);
291 PolicyLogger.error("Unsupported data object."
292 + policyAdapter.getData().getClass().getCanonicalName());
294 setPreparedToSave(true);
298 // Data required for Advice part is setting here.
299 private AdviceExpressionsType getAdviceExpressions(int version,
302 // Policy Config ID Assignment
303 AdviceExpressionsType advices = new AdviceExpressionsType();
304 AdviceExpressionType advice = new AdviceExpressionType();
305 advice.setAdviceId("BRMSRAWID");
306 advice.setAppliesTo(EffectType.PERMIT);
308 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
309 assignment1.setAttributeId("type");
310 assignment1.setCategory(CATEGORY_RESOURCE);
311 assignment1.setIssuer("");
312 AttributeValueType configNameAttributeValue = new AttributeValueType();
313 configNameAttributeValue.setDataType(STRING_DATATYPE);
314 configNameAttributeValue.getContent().add("Configuration");
315 assignment1.setExpression(new ObjectFactory()
316 .createAttributeValue(configNameAttributeValue));
317 advice.getAttributeAssignmentExpression().add(assignment1);
319 // For Config file Url if configurations are provided.
321 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
322 assignment2.setAttributeId("URLID");
323 assignment2.setCategory(CATEGORY_RESOURCE);
324 assignment2.setIssuer("");
325 AttributeValueType AttributeValue = new AttributeValueType();
326 AttributeValue.setDataType(URI_DATATYPE);
328 String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
330 AttributeValue.getContent().add(content);
331 assignment2.setExpression(new ObjectFactory()
332 .createAttributeValue(AttributeValue));
333 advice.getAttributeAssignmentExpression().add(assignment2);
335 // Policy Name Assignment
336 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
337 assignment3.setAttributeId("PolicyName");
338 assignment3.setCategory(CATEGORY_RESOURCE);
339 assignment3.setIssuer("");
340 AttributeValueType attributeValue3 = new AttributeValueType();
341 attributeValue3.setDataType(STRING_DATATYPE);
342 fileName = FilenameUtils.removeExtension(fileName);
343 fileName = fileName + ".xml";
344 System.out.println(fileName);
345 String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
347 if ((name == null) || (name.equals(""))) {
348 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("");
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("");
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("");
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()).getController()));
401 // Adding Dependencies.
402 if(policyAdapter.getBrmsDependency()!=null){
403 BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
404 ArrayList<String> dependencies = new ArrayList<>();
405 StringBuilder key = new StringBuilder();
406 for(String dependencyName: policyAdapter.getBrmsDependency()){
407 dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
408 key.append(dependencyName + ",");
410 advice.getAttributeAssignmentExpression().add(
411 createResponseAttributes("dependencies:"+key.toString(), dependencies.toString()));
414 // Dynamic Field Config Attributes.
415 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
416 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
417 advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField)));
421 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
422 assignment8.setAttributeId("RiskType");
423 assignment8.setCategory(CATEGORY_RESOURCE);
424 assignment8.setIssuer("");
426 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
427 configNameAttributeValue8.setDataType(STRING_DATATYPE);
428 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
429 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
431 advice.getAttributeAssignmentExpression().add(assignment8);
433 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
434 assignment9.setAttributeId("RiskLevel");
435 assignment9.setCategory(CATEGORY_RESOURCE);
436 assignment9.setIssuer("");
438 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
439 configNameAttributeValue9.setDataType(STRING_DATATYPE);
440 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
441 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
443 advice.getAttributeAssignmentExpression().add(assignment9);
445 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
446 assignment10.setAttributeId("guard");
447 assignment10.setCategory(CATEGORY_RESOURCE);
448 assignment10.setIssuer("");
450 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
451 configNameAttributeValue10.setDataType(STRING_DATATYPE);
452 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
453 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
455 advice.getAttributeAssignmentExpression().add(assignment10);
457 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
458 assignment11.setAttributeId("TTLDate");
459 assignment11.setCategory(CATEGORY_RESOURCE);
460 assignment11.setIssuer("");
462 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
463 configNameAttributeValue11.setDataType(STRING_DATATYPE);
464 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
465 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
467 advice.getAttributeAssignmentExpression().add(assignment11);
469 advices.getAdviceExpression().add(advice);
474 public Object getCorrectPolicyDataObject() {
475 return policyAdapter.getData();
478 private AttributeAssignmentExpressionType createResponseAttributes(String key, String value){
479 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
480 assignment7.setAttributeId(key);
481 assignment7.setCategory(CATEGORY_RESOURCE);
482 assignment7.setIssuer("");
483 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
484 configNameAttributeValue7.setDataType(STRING_DATATYPE);
485 configNameAttributeValue7.getContent().add(value);
486 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));