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;
24 import java.io.IOException;
25 import java.io.PrintWriter;
27 import java.net.URISyntaxException;
28 import java.nio.charset.Charset;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.HashMap;
34 import java.util.StringTokenizer;
36 import javax.json.stream.JsonGenerationException;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
52 import org.apache.commons.io.FilenameUtils;
53 import org.apache.commons.logging.Log;
54 import org.apache.commons.logging.LogFactory;
55 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
57 import com.att.research.xacml.std.IdentifierImpl;
59 import org.openecomp.policy.common.logging.eelf.MessageCodes;
60 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
61 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
62 import org.openecomp.policy.common.logging.flexlogger.Logger;
64 public class ClosedLoopPolicy extends Policy {
69 private static final Logger logger = FlexLogger.getLogger(ConfigPolicy.class);
71 public ClosedLoopPolicy() {
75 public ClosedLoopPolicy(PolicyRestAdapter policyAdapter){
76 this.policyAdapter = policyAdapter;
79 //save configuration of the policy based on the policyname
80 private void saveConfigurations(String policyName, String prevPolicyName, String jsonBody) {
81 String domain = getParentPathSubScopeDir();
82 String path = domain.replace('\\', '.');
83 if(path.contains("/")){
84 path = domain.replace('/', '.');
85 logger.info("print the path:" +path);
88 String body = jsonBody;
91 //Remove the trapMaxAge in Verification Signature
92 body = body.replace(",\"trapMaxAge\":null", "");
94 logger.debug("No Trap Max Age in JSON body");
96 this.policyAdapter.setJsonBody(body);
97 } catch (Exception e) {
101 System.out.println(body);
102 if(policyName.endsWith(".xml")){
103 policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
105 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator+path + "."+ policyName +".json");
109 } catch (JsonGenerationException e) {
111 } catch (IOException e) {
117 //Utility to read json data from the existing file to a string
118 static String readFile(String path, Charset encoding) throws IOException {
120 byte[] encoded = Files.readAllBytes(Paths.get(path));
121 return new String(encoded, encoding);
125 //create the configuration file based on the policy name on adding the extension as .json
126 private String getConfigFile(String filename) {
127 filename = FilenameUtils.removeExtension(filename);
128 if (filename.endsWith(".xml")) {
129 filename = filename.substring(0, filename.length() - 4);
131 filename = filename + ".json";
136 public Map<String, String> savePolicies() throws Exception {
138 Map<String, String> successMap = new HashMap<String,String>();
139 if(isPolicyExists()){
140 successMap.put("EXISTS", "This Policy already exist on the PAP");
144 if(!isPreparedToSave()){
148 // Until here we prepared the data and here calling the method to create xml.
149 Path newPolicyPath = null;
150 newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(), policyName);
152 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
153 if (successMap.containsKey("success")) {
154 Path finalPolicyPath = getFinalPolicyPath();
155 policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
160 //This is the method for preparing the policy for saving. We have broken it out
161 //separately because the fully configured policy is used for multiple things
163 public boolean prepareToSave() throws Exception{
165 if(isPreparedToSave()){
166 //we have already done this
171 String policyID = policyAdapter.getPolicyID();
173 if (policyAdapter.isEditPolicy()) {
174 version = policyAdapter.getHighestVersion() + 1;
179 // Create the Instance for pojo, PolicyType object is used in marshalling.
180 if (policyAdapter.getPolicyType().equals("Config")) {
181 PolicyType policyConfig = new PolicyType();
183 policyConfig.setVersion(Integer.toString(version));
184 policyConfig.setPolicyId(policyID);
185 policyConfig.setTarget(new TargetType());
186 policyAdapter.setData(policyConfig);
189 if (policyAdapter.getData() != null) {
191 //delete the closed loop draft file and configuration file, if validation is success after editing the draft policy
192 String prevPolicyName = null;
193 if(policyAdapter.isEditPolicy()){
194 prevPolicyName = "Config_Fault_" + policyAdapter.getPolicyName() + "." + policyAdapter.getHighestVersion() + ".xml";
196 if (policyAdapter.isDraft()) {
197 policyName = "Config_Fault_" + policyAdapter.getPolicyName() + "_Draft";
199 policyName = "Config_Fault_" + policyAdapter.getPolicyName();
202 //delete the closed loop draft configuration file, if validation is success after editing the draft policy
203 final Path gitPath = Paths.get(policyAdapter.getUserGitPath());
204 String policyDir = policyAdapter.getParentPath();
205 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
206 policyDir = policyDir.substring(startIndex, policyDir.length());
207 logger.info("print the main domain value"+policyDir);
208 String path = policyDir.replace('\\', '.');
209 if(path.contains("/")){
210 path = policyDir.replace('/', '.');
211 logger.info("print the path:" +path);
213 String fileName = FilenameUtils.removeExtension(policyName);
215 final String tempPath = path;
216 String fileLocation = null;
217 if (fileName != null && fileName.contains("Config_Fault_")) {
218 fileLocation = CONFIG_HOME;
220 // Get the file from the saved location
221 File dir = new File(fileLocation);
222 File[] listOfFiles = dir.listFiles();
223 for (File file : listOfFiles) {
224 String configFile = null;
225 if(!policyAdapter.isDraft()){
226 configFile = fileName + "_Draft";
228 configFile = fileName;
230 if (file.isFile() && file.getName().contains( tempPath + "." + configFile)) {
232 if (file.delete() == false) {
234 "No known error, Delete failed");
236 } catch (Exception e) {
237 logger.error("Failed to Delete file: "
238 + e.getLocalizedMessage());
244 // Save off everything
245 // making ready all the required elements to generate the action policy xml.
246 // Get the uniqueness for policy name.
247 String policyName1 = null;
248 if(policyAdapter.isDraft()){
249 policyName1 = policyAdapter.getPolicyName() + "_Draft";
251 policyName1 = policyAdapter.getPolicyName();
254 Path newFile = this.getNextLoopFilename(Paths.get(policyAdapter.getParentPath()), policyAdapter.getPolicyType(), policyAdapter.getConfigPolicyType(), policyName1, version);
255 if (newFile == null) {
256 //TODO:EELF Cleanup - Remove logger
257 //logger.error("File already exists, cannot create the policy.");
258 PolicyLogger.error("File already exists, cannot create the policy.");
259 setPolicyExists(true);
263 policyName = newFile.getFileName().toString();
265 // Save the Configurations file with the policy name with extention based on selection.
266 String jsonBody = policyAdapter.getJsonBody();
267 saveConfigurations(policyName, prevPolicyName, jsonBody);
269 // Make sure the filename ends with an extension
270 if (policyName.endsWith(".xml") == false) {
271 policyName = policyName + ".xml";
274 PolicyType faultPolicy = (PolicyType) policyAdapter.getData();
276 faultPolicy.setDescription(policyAdapter.getPolicyDescription());
278 faultPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
280 AllOfType allOfOne = new AllOfType();
281 File policyFilePath = new File(policyAdapter.getParentPath().toString(), policyName);
282 String policyDir = policyFilePath.getParentFile().getName();
283 String fileName = FilenameUtils.removeExtension(policyName);
284 fileName = policyDir + "." + fileName + ".xml";
285 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
286 if ((name == null) || (name.equals(""))) {
287 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
289 allOfOne.getMatch().add(createMatch("PolicyName", name));
290 AllOfType allOf = new AllOfType();
291 // Adding the matches to AllOfType element
293 allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName()));
294 // Match for riskType
295 allOf.getMatch().add(
296 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
297 // Match for riskLevel
298 allOf.getMatch().add(
299 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
300 // Match for riskguard
301 allOf.getMatch().add(
302 createDynamicMatch("guard", policyAdapter.getGuard()));
304 allOf.getMatch().add(
305 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
307 AnyOfType anyOf = new AnyOfType();
308 anyOf.getAllOf().add(allOfOne);
309 anyOf.getAllOf().add(allOf);
311 TargetType target = new TargetType();
312 ((TargetType) target).getAnyOf().add(anyOf);
313 // Adding the target to the policy element
314 faultPolicy.setTarget((TargetType) target);
316 RuleType rule = new RuleType();
317 rule.setRuleId(policyAdapter.getRuleID());
318 rule.setEffect(EffectType.PERMIT);
320 // Create Target in Rule
321 AllOfType allOfInRule = new AllOfType();
323 // Creating match for ACCESS in rule target
324 MatchType accessMatch = new MatchType();
325 AttributeValueType accessAttributeValue = new AttributeValueType();
326 accessAttributeValue.setDataType(STRING_DATATYPE);
327 accessAttributeValue.getContent().add("ACCESS");
328 accessMatch.setAttributeValue(accessAttributeValue);
329 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
330 URI accessURI = null;
332 accessURI = new URI(ACTION_ID);
333 } catch (URISyntaxException e) {
334 //TODO:EELF Cleanup - Remove logger
335 //logger.error(e.getStackTrace());
336 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating ACCESS URI");
338 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
339 accessAttributeDesignator.setDataType(STRING_DATATYPE);
340 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
341 accessMatch.setAttributeDesignator(accessAttributeDesignator);
342 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
344 // Creating Config Match in rule Target
345 MatchType closedMatch = new MatchType();
346 AttributeValueType closedAttributeValue = new AttributeValueType();
347 closedAttributeValue.setDataType(STRING_DATATYPE);
348 closedAttributeValue.getContent().add("Config");
349 closedMatch.setAttributeValue(closedAttributeValue);
350 AttributeDesignatorType closedAttributeDesignator = new AttributeDesignatorType();
351 URI closedURI = null;
353 closedURI = new URI(RESOURCE_ID);
354 } catch (URISyntaxException e) {
355 //TODO:EELF Cleanup - Remove logger
356 //logger.error(e.getStackTrace());
357 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateClosedLoopPolicy", "Exception creating closed URI");
359 closedAttributeDesignator.setCategory(CATEGORY_RESOURCE);
360 closedAttributeDesignator.setDataType(STRING_DATATYPE);
361 closedAttributeDesignator.setAttributeId(new IdentifierImpl(closedURI).stringValue());
362 closedMatch.setAttributeDesignator(closedAttributeDesignator);
363 closedMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
365 allOfInRule.getMatch().add(accessMatch);
366 allOfInRule.getMatch().add(closedMatch);
368 AnyOfType anyOfInRule = new AnyOfType();
369 anyOfInRule.getAllOf().add(allOfInRule);
371 TargetType targetInRule = new TargetType();
372 targetInRule.getAnyOf().add(anyOfInRule);
374 rule.setTarget(targetInRule);
375 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
377 faultPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
378 policyAdapter.setPolicyData(faultPolicy);
381 //TODO:EELF Cleanup - Remove logger
382 //logger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
383 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
386 setPreparedToSave(true);
390 // Data required for Advice part is setting here.
391 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
392 AdviceExpressionsType advices = new AdviceExpressionsType();
393 AdviceExpressionType advice = new AdviceExpressionType();
394 advice.setAdviceId("faultID");
395 advice.setAppliesTo(EffectType.PERMIT);
397 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
398 assignment1.setAttributeId("type");
399 assignment1.setCategory(CATEGORY_RESOURCE);
400 assignment1.setIssuer("");
402 AttributeValueType configNameAttributeValue = new AttributeValueType();
403 configNameAttributeValue.setDataType(STRING_DATATYPE);
404 configNameAttributeValue.getContent().add("Configuration");
405 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
407 advice.getAttributeAssignmentExpression().add(assignment1);
408 final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
409 // For Config file Url if configurations are provided.
410 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
411 assignment2.setAttributeId("URLID");
412 assignment2.setCategory(CATEGORY_RESOURCE);
413 assignment2.setIssuer("");
415 AttributeValueType AttributeValue = new AttributeValueType();
416 AttributeValue.setDataType(URI_DATATYPE);
417 String policyDir1 = policyAdapter.getParentPath().toString();
418 int startIndex1 = policyDir1.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
419 policyDir1 = policyDir1.substring(startIndex1, policyDir1.length());
420 logger.info("print the main domain value"+policyDir1);
421 String path = policyDir1.replace('\\', '.');
422 if(path.contains("/")){
423 path = policyDir1.replace('/', '.');
424 logger.info("print the path:" +path);
427 String content = CONFIG_URL +"/Config/" + path + "." + getConfigFile(policyName);
428 System.out.println("URL value :" + content);
429 AttributeValue.getContent().add(content);
430 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
432 advice.getAttributeAssignmentExpression().add(assignment2);
433 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
434 assignment3.setAttributeId("PolicyName");
435 assignment3.setCategory(CATEGORY_RESOURCE);
436 assignment3.setIssuer("");
438 AttributeValueType attributeValue3 = new AttributeValueType();
439 attributeValue3.setDataType(STRING_DATATYPE);
440 String policyDir = policyAdapter.getParentPath().toString();
441 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
442 policyDir = policyDir.substring(startIndex, policyDir.length());
443 StringTokenizer tokenizer = null;
444 StringBuffer buffer = new StringBuffer();
445 if (policyDir.contains("\\")) {
446 tokenizer = new StringTokenizer(policyDir, "\\");
448 tokenizer = new StringTokenizer(policyDir, "/");
450 if (tokenizer != null) {
451 while (tokenizer.hasMoreElements()) {
452 String value = tokenizer.nextToken();
453 buffer.append(value);
457 fileName = FilenameUtils.removeExtension(fileName);
458 fileName = buffer.toString() + fileName + ".xml";
459 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
460 if ((name == null) || (name.equals(""))) {
461 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
463 attributeValue3.getContent().add(name);
464 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
465 advice.getAttributeAssignmentExpression().add(assignment3);
467 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
468 assignment4.setAttributeId("VersionNumber");
469 assignment4.setCategory(CATEGORY_RESOURCE);
470 assignment4.setIssuer("");
472 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
473 configNameAttributeValue4.setDataType(STRING_DATATYPE);
474 configNameAttributeValue4.getContent().add(Integer.toString(version));
475 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
477 advice.getAttributeAssignmentExpression().add(assignment4);
479 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
480 assignment5.setAttributeId("matching:" + this.ECOMPID);
481 assignment5.setCategory(CATEGORY_RESOURCE);
482 assignment5.setIssuer("");
484 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
485 configNameAttributeValue5.setDataType(STRING_DATATYPE);
486 configNameAttributeValue5.getContent().add(policyAdapter.getEcompName());
487 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
489 advice.getAttributeAssignmentExpression().add(assignment5);
492 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
493 assignment6.setAttributeId("RiskType");
494 assignment6.setCategory(CATEGORY_RESOURCE);
495 assignment6.setIssuer("");
497 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
498 configNameAttributeValue6.setDataType(STRING_DATATYPE);
499 configNameAttributeValue6.getContent().add(policyAdapter.getRiskType());
500 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
502 advice.getAttributeAssignmentExpression().add(assignment6);
504 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
505 assignment7.setAttributeId("RiskLevel");
506 assignment7.setCategory(CATEGORY_RESOURCE);
507 assignment7.setIssuer("");
509 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
510 configNameAttributeValue7.setDataType(STRING_DATATYPE);
511 configNameAttributeValue7.getContent().add(policyAdapter.getRiskLevel());
512 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
514 advice.getAttributeAssignmentExpression().add(assignment7);
516 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
517 assignment8.setAttributeId("guard");
518 assignment8.setCategory(CATEGORY_RESOURCE);
519 assignment8.setIssuer("");
521 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
522 configNameAttributeValue8.setDataType(STRING_DATATYPE);
523 configNameAttributeValue8.getContent().add(policyAdapter.getGuard());
524 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
526 advice.getAttributeAssignmentExpression().add(assignment8);
528 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
529 assignment9.setAttributeId("TTLDate");
530 assignment9.setCategory(CATEGORY_RESOURCE);
531 assignment9.setIssuer("");
533 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
534 configNameAttributeValue9.setDataType(STRING_DATATYPE);
535 configNameAttributeValue9.getContent().add(policyAdapter.getTtlDate());
536 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
538 advice.getAttributeAssignmentExpression().add(assignment9);
542 advices.getAdviceExpression().add(advice);
547 public Object getCorrectPolicyDataObject() {
548 return policyAdapter.getPolicyData();