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.openecomp.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.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;
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<String,String>();
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 Boolean dbIsUpdated = true;
136 successMap = new HashMap<String, String>();
138 successMap = createPolicy(newPolicyPath,
139 getCorrectPolicyDataObject());
141 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
142 successMap.put("error", "DB UPDATE");
148 // This is the method for preparing the policy for saving. We have broken it
150 // separately because the fully configured policy is used for multiple
153 public boolean prepareToSave() throws Exception {
155 if (isPreparedToSave()) {
156 // we have already done this
161 String policyID = policyAdapter.getPolicyID();
162 version = policyAdapter.getHighestVersion();
164 // Create the Instance for pojo, PolicyType object is used in
166 if (policyAdapter.getPolicyType().equals("Config")) {
167 PolicyType policyConfig = new PolicyType();
169 policyConfig.setVersion(Integer.toString(version));
170 policyConfig.setPolicyId(policyID);
171 policyConfig.setTarget(new TargetType());
172 policyAdapter.setData(policyConfig);
175 policyName = policyAdapter.getNewFileName();
177 if (policyAdapter.getData() != null) {
178 //String jsonBody = policyAdapter.getJsonBody();
179 String configBody=policyAdapter.getConfigBodyData();
180 saveConfigurations(policyName, configBody);
182 // Make sure the filename ends with an extension
183 if (policyName.endsWith(".xml") == false) {
184 policyName = policyName + ".xml";
187 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
189 configPolicy.setDescription(policyAdapter.getPolicyDescription());
191 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
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,
200 allOfOne.getMatch().add(createMatch("PolicyName", name));
203 AllOfType allOf = new AllOfType();
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()));
215 allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
216 AnyOfType anyOf = new AnyOfType();
217 anyOf.getAllOf().add(allOfOne);
218 anyOf.getAllOf().add(allOf);
220 TargetType target = new TargetType();
221 ((TargetType) target).getAnyOf().add(anyOf);
223 // Adding the target to the policy element
224 configPolicy.setTarget((TargetType) target);
226 RuleType rule = new RuleType();
227 rule.setRuleId(policyAdapter.getRuleID());
229 rule.setEffect(EffectType.PERMIT);
231 // Create Target in Rule
232 AllOfType allOfInRule = new AllOfType();
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;
243 accessURI = new URI(ACTION_ID);
244 } catch (URISyntaxException e) {
245 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating ACCESS URI");
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);
254 // Creating Config Match in rule Target
255 MatchType configMatch = new MatchType();
256 AttributeValueType configAttributeValue = new AttributeValueType();
257 configAttributeValue.setDataType(STRING_DATATYPE);
259 configAttributeValue.getContent().add("Config");
261 configMatch.setAttributeValue(configAttributeValue);
262 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
263 URI configURI = null;
265 configURI = new URI(RESOURCE_ID);
266 } catch (URISyntaxException e) {
267 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsRawPolicy", "Exception creating Config URI");
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);
277 allOfInRule.getMatch().add(accessMatch);
278 allOfInRule.getMatch().add(configMatch);
280 AnyOfType anyOfInRule = new AnyOfType();
281 anyOfInRule.getAllOf().add(allOfInRule);
283 TargetType targetInRule = new TargetType();
284 targetInRule.getAnyOf().add(anyOfInRule);
286 rule.setTarget(targetInRule);
287 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
290 .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
292 policyAdapter.setPolicyData(configPolicy);
295 PolicyLogger.error("Unsupported data object."
296 + policyAdapter.getData().getClass().getCanonicalName());
298 setPreparedToSave(true);
302 // Data required for Advice part is setting here.
303 private AdviceExpressionsType getAdviceExpressions(int version,
306 // Policy Config ID Assignment
307 AdviceExpressionsType advices = new AdviceExpressionsType();
308 AdviceExpressionType advice = new AdviceExpressionType();
309 advice.setAdviceId("BRMSRAWID");
310 advice.setAppliesTo(EffectType.PERMIT);
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);
323 // For Config file Url if configurations are provided.
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);
332 String content = CONFIG_URL + "/Config/" + getConfigFile(policyName);
334 AttributeValue.getContent().add(content);
335 assignment2.setExpression(new ObjectFactory()
336 .createAttributeValue(AttributeValue));
337 advice.getAttributeAssignmentExpression().add(assignment2);
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,
351 if ((name == null) || (name.equals(""))) {
352 name = fileName.substring(fileName.lastIndexOf("/") + 1,
355 System.out.println(name);
356 attributeValue3.getContent().add(name);
357 assignment3.setExpression(new ObjectFactory()
358 .createAttributeValue(attributeValue3));
359 advice.getAttributeAssignmentExpression().add(assignment3);
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);
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);
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);
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()));
405 // Adding Dependencies.
406 if(policyAdapter.getBrmsDependency()!=null){
407 BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
408 ArrayList<String> dependencies = new ArrayList<String>();
409 StringBuilder key = new StringBuilder();
410 for(String dependencyName: policyAdapter.getBrmsDependency()){
411 dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
412 key.append(dependencyName + ",");
414 advice.getAttributeAssignmentExpression().add(
415 createResponseAttributes("dependencies:"+key.toString(), dependencies.toString()));
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)));
425 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
426 assignment8.setAttributeId("RiskType");
427 assignment8.setCategory(CATEGORY_RESOURCE);
428 assignment8.setIssuer("");
430 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
431 configNameAttributeValue8.setDataType(STRING_DATATYPE);
432 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
433 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
435 advice.getAttributeAssignmentExpression().add(assignment8);
437 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
438 assignment9.setAttributeId("RiskLevel");
439 assignment9.setCategory(CATEGORY_RESOURCE);
440 assignment9.setIssuer("");
442 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
443 configNameAttributeValue9.setDataType(STRING_DATATYPE);
444 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
445 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
447 advice.getAttributeAssignmentExpression().add(assignment9);
449 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
450 assignment10.setAttributeId("guard");
451 assignment10.setCategory(CATEGORY_RESOURCE);
452 assignment10.setIssuer("");
454 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
455 configNameAttributeValue10.setDataType(STRING_DATATYPE);
456 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
457 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
459 advice.getAttributeAssignmentExpression().add(assignment10);
461 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
462 assignment11.setAttributeId("TTLDate");
463 assignment11.setCategory(CATEGORY_RESOURCE);
464 assignment11.setIssuer("");
466 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
467 configNameAttributeValue11.setDataType(STRING_DATATYPE);
468 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
469 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
471 advice.getAttributeAssignmentExpression().add(assignment11);
473 advices.getAdviceExpression().add(advice);
478 public Object getCorrectPolicyDataObject() {
479 return policyAdapter.getData();
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));