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.file.Path;
30 import java.nio.file.Paths;
31 import java.util.HashMap;
33 import java.util.StringTokenizer;
35 import javax.json.stream.JsonGenerationException;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
51 import org.apache.commons.io.FilenameUtils;
52 import org.apache.commons.logging.Log;
53 import org.apache.commons.logging.LogFactory;
54 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
56 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
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 CreateClosedLoopPerformanceMetrics extends Policy {
69 private static final Logger logger = FlexLogger.getLogger(ConfigPolicy.class);
71 public CreateClosedLoopPerformanceMetrics() {
75 public CreateClosedLoopPerformanceMetrics(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);
91 } catch (Exception e) {
95 System.out.println(body);
96 if(policyName.endsWith(".xml")){
97 policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
99 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator+path + "."+ policyName +".json");
103 } catch (JsonGenerationException e) {
105 } catch (IOException e) {
111 //getting the policy name and setting to configuration on adding .json
112 private String getConfigFile(String filename) {
113 filename = FilenameUtils.removeExtension(filename);
114 if (filename.endsWith(".xml")) {
115 filename = filename.substring(0, filename.length() - 4);
117 filename = filename +".json";
122 public Map<String, String> savePolicies() throws Exception {
124 Map<String, String> successMap = new HashMap<String,String>();
125 if(isPolicyExists()){
126 successMap.put("EXISTS", "This Policy already exist on the PAP");
130 if(!isPreparedToSave()){
131 //Prep and configure the policy for saving
135 // Until here we prepared the data and here calling the method to create xml.
136 Path newPolicyPath = null;
137 newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(), policyName);
138 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() );
139 if (successMap.containsKey("success")) {
140 Path finalPolicyPath = getFinalPolicyPath();
141 policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
146 //This is the method for preparing the policy for saving. We have broken it out
147 //separately because the fully configured policy is used for multiple things
149 public boolean prepareToSave() throws Exception{
151 if(isPreparedToSave()){
152 //we have already done this
157 String policyID = policyAdapter.getPolicyID();
159 if (policyAdapter.isEditPolicy()) {
160 version = policyAdapter.getHighestVersion() + 1;
165 // Create the Instance for pojo, PolicyType object is used in marshalling.
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 if (policyAdapter.getData() != null) {
177 // Save off everything
178 // making ready all the required elements to generate the action policy xml.
179 // Get the uniqueness for policy name.
180 String prevPolicyName = null;
181 if(policyAdapter.isEditPolicy()){
182 prevPolicyName = "Config_PM_" + policyAdapter.getPolicyName() + "." + policyAdapter.getHighestVersion() + ".xml";
185 Path newFile = this.getNextLoopFilename(Paths.get(policyAdapter.getParentPath()), policyAdapter.getPolicyType(), policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), version);
187 if (newFile == null) {
188 //TODO:EELF Cleanup - Remove logger
189 //logger.error("File already exists, cannot create the policy.");
190 PolicyLogger.error("File already exists, cannot create the policy.");
191 setPolicyExists(true);
195 policyName = newFile.getFileName().toString();
197 // Save the Configurations file with the policy name with extention based on selection.
198 String jsonBody = policyAdapter.getJsonBody();
199 saveConfigurations(policyName, prevPolicyName, jsonBody);
201 // Make sure the filename ends with an extension
202 if (policyName.endsWith(".xml") == false) {
203 policyName = policyName + ".xml";
207 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
209 configPolicy.setDescription(policyAdapter.getPolicyDescription());
211 configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
213 AllOfType allOfOne = new AllOfType();
214 final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
215 String policyDir = policyAdapter.getParentPath().toString();
216 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
217 policyDir = policyDir.substring(startIndex, policyDir.length());
218 logger.info("print the main domain value "+policyDir);
219 String path = policyDir.replace('\\', '.');
220 if(path.contains("/")){
221 path = policyDir.replace('/', '.');
222 logger.info("print the path:" +path);
224 String fileName = FilenameUtils.removeExtension(policyName);
225 fileName = path + "." + fileName + ".xml";
226 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
227 if ((name == null) || (name.equals(""))) {
228 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
230 allOfOne.getMatch().add(createMatch("PolicyName", name));
231 AllOfType allOf = new AllOfType();
233 // Adding the matches to AllOfType element Match for Ecomp
234 allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName()));
235 // Match for riskType
236 allOf.getMatch().add(
237 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
238 // Match for riskLevel
239 allOf.getMatch().add(
240 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
241 // Match for riskguard
242 allOf.getMatch().add(
243 createDynamicMatch("guard", policyAdapter.getGuard()));
245 allOf.getMatch().add(
246 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
247 // Match for ServiceType
248 allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType()));
250 AnyOfType anyOf = new AnyOfType();
251 anyOf.getAllOf().add(allOfOne);
252 anyOf.getAllOf().add(allOf);
254 TargetType target = new TargetType();
255 ((TargetType) target).getAnyOf().add(anyOf);
257 // Adding the target to the policy element
258 configPolicy.setTarget((TargetType) target);
260 RuleType rule = new RuleType();
261 rule.setRuleId(policyAdapter.getRuleID());
263 rule.setEffect(EffectType.PERMIT);
265 // Create Target in Rule
266 AllOfType allOfInRule = new AllOfType();
268 // Creating match for ACCESS in rule target
269 MatchType accessMatch = new MatchType();
270 AttributeValueType accessAttributeValue = new AttributeValueType();
271 accessAttributeValue.setDataType(STRING_DATATYPE);
272 accessAttributeValue.getContent().add("ACCESS");
273 accessMatch.setAttributeValue(accessAttributeValue);
274 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
275 URI accessURI = null;
277 accessURI = new URI(ACTION_ID);
278 } catch (URISyntaxException e) {
279 //TODO:EELF Cleanup - Remove logger
280 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
281 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI");
283 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
284 accessAttributeDesignator.setDataType(STRING_DATATYPE);
285 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
286 accessMatch.setAttributeDesignator(accessAttributeDesignator);
287 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
289 // Creating Config Match in rule Target
290 MatchType configMatch = new MatchType();
291 AttributeValueType configAttributeValue = new AttributeValueType();
292 configAttributeValue.setDataType(STRING_DATATYPE);
293 configAttributeValue.getContent().add("Config");
294 configMatch.setAttributeValue(configAttributeValue);
295 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
296 URI configURI = null;
298 configURI = new URI(RESOURCE_ID);
299 } catch (URISyntaxException e) {
300 //TODO:EELF Cleanup - Remove logger
301 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
302 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI");
304 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
305 configAttributeDesignator.setDataType(STRING_DATATYPE);
306 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
307 configMatch.setAttributeDesignator(configAttributeDesignator);
308 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
310 allOfInRule.getMatch().add(accessMatch);
311 allOfInRule.getMatch().add(configMatch);
313 AnyOfType anyOfInRule = new AnyOfType();
314 anyOfInRule.getAllOf().add(allOfInRule);
316 TargetType targetInRule = new TargetType();
317 targetInRule.getAnyOf().add(anyOfInRule);
319 rule.setTarget(targetInRule);
320 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
322 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
323 policyAdapter.setPolicyData(configPolicy);
326 //TODO:EELF Cleanup - Remove logger
327 //logger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
328 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
330 setPreparedToSave(true);
334 // Data required for Advice part is setting here.
335 @SuppressWarnings("static-access")
336 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
337 AdviceExpressionsType advices = new AdviceExpressionsType();
338 AdviceExpressionType advice = new AdviceExpressionType();
339 advice.setAdviceId("PMID");
340 advice.setAppliesTo(EffectType.PERMIT);
342 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
343 assignment1.setAttributeId("type");
344 assignment1.setCategory(CATEGORY_RESOURCE);
345 assignment1.setIssuer("");
347 AttributeValueType configNameAttributeValue = new AttributeValueType();
348 configNameAttributeValue.setDataType(STRING_DATATYPE);
349 configNameAttributeValue.getContent().add("Configuration");
350 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
352 advice.getAttributeAssignmentExpression().add(assignment1);
353 final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
354 // For Config file Url if configurations are provided.
355 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
356 assignment2.setAttributeId("URLID");
357 assignment2.setCategory(CATEGORY_RESOURCE);
358 assignment2.setIssuer("");
360 AttributeValueType AttributeValue = new AttributeValueType();
361 AttributeValue.setDataType(URI_DATATYPE);
362 String policyDir1 = policyAdapter.getParentPath().toString();
363 int startIndex1 = policyDir1.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
364 policyDir1 = policyDir1.substring(startIndex1, policyDir1.length());
365 logger.info("print the main domain value"+policyDir1);
366 String path = policyDir1.replace('\\', '.');
367 if(path.contains("/")){
368 path = policyDir1.replace('/', '.');
369 logger.info("print the path:" +path);
371 String content = CONFIG_URL +"/Config/" + path + "." + getConfigFile(policyName);
372 System.out.println("URL value :" + content);
373 AttributeValue.getContent().add(content);
374 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
376 advice.getAttributeAssignmentExpression().add(assignment2);
377 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
378 assignment3.setAttributeId("PolicyName");
379 assignment3.setCategory(CATEGORY_RESOURCE);
380 assignment3.setIssuer("");
382 AttributeValueType attributeValue3 = new AttributeValueType();
383 attributeValue3.setDataType(STRING_DATATYPE);
384 String policyDir = policyAdapter.getParentPath().toString();
385 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
386 policyDir = policyDir.substring(startIndex, policyDir.length());
387 StringTokenizer tokenizer = null;
388 StringBuffer buffer = new StringBuffer();
389 if (policyDir.contains("\\")) {
390 tokenizer = new StringTokenizer(policyDir, "\\");
392 tokenizer = new StringTokenizer(policyDir, "/");
394 if (tokenizer != null) {
395 while (tokenizer.hasMoreElements()) {
396 String value = tokenizer.nextToken();
397 buffer.append(value);
401 fileName = FilenameUtils.removeExtension(fileName);
402 fileName = buffer.toString() + fileName + ".xml";
403 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
404 if ((name == null) || (name.equals(""))) {
405 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
407 attributeValue3.getContent().add(name);
408 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
409 advice.getAttributeAssignmentExpression().add(assignment3);
411 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
412 assignment4.setAttributeId("VersionNumber");
413 assignment4.setCategory(CATEGORY_RESOURCE);
414 assignment4.setIssuer("");
416 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
417 configNameAttributeValue4.setDataType(STRING_DATATYPE);
418 configNameAttributeValue4.getContent().add(Integer.toString(version));
419 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
421 advice.getAttributeAssignmentExpression().add(assignment4);
423 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
424 assignment5.setAttributeId("matching:" + this.ECOMPID);
425 assignment5.setCategory(CATEGORY_RESOURCE);
426 assignment5.setIssuer("");
428 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
429 configNameAttributeValue5.setDataType(STRING_DATATYPE);
430 configNameAttributeValue5.getContent().add(policyAdapter.getEcompName());
431 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
433 advice.getAttributeAssignmentExpression().add(assignment5);
435 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
436 assignment6.setAttributeId("matching:" + this.CLOSEDLOOPID);
437 assignment6.setCategory(CATEGORY_RESOURCE);
438 assignment6.setIssuer("");
440 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
441 configNameAttributeValue6.setDataType(STRING_DATATYPE);
442 configNameAttributeValue6.getContent().add(policyAdapter.getServiceType());
443 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
445 advice.getAttributeAssignmentExpression().add(assignment6);
448 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
449 assignment7.setAttributeId("RiskType");
450 assignment7.setCategory(CATEGORY_RESOURCE);
451 assignment7.setIssuer("");
453 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
454 configNameAttributeValue7.setDataType(STRING_DATATYPE);
455 configNameAttributeValue7.getContent().add(policyAdapter.getRiskType());
456 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
458 advice.getAttributeAssignmentExpression().add(assignment7);
460 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
461 assignment8.setAttributeId("RiskLevel");
462 assignment8.setCategory(CATEGORY_RESOURCE);
463 assignment8.setIssuer("");
465 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
466 configNameAttributeValue8.setDataType(STRING_DATATYPE);
467 configNameAttributeValue8.getContent().add(policyAdapter.getRiskLevel());
468 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
470 advice.getAttributeAssignmentExpression().add(assignment8);
472 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
473 assignment9.setAttributeId("guard");
474 assignment9.setCategory(CATEGORY_RESOURCE);
475 assignment9.setIssuer("");
477 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
478 configNameAttributeValue9.setDataType(STRING_DATATYPE);
479 configNameAttributeValue9.getContent().add(policyAdapter.getGuard());
480 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
482 advice.getAttributeAssignmentExpression().add(assignment9);
484 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
485 assignment10.setAttributeId("TTLDate");
486 assignment10.setCategory(CATEGORY_RESOURCE);
487 assignment10.setIssuer("");
489 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
490 configNameAttributeValue10.setDataType(STRING_DATATYPE);
491 configNameAttributeValue10.getContent().add(policyAdapter.getTtlDate());
492 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
494 advice.getAttributeAssignmentExpression().add(assignment10);
496 advices.getAdviceExpression().add(advice);
501 public Object getCorrectPolicyDataObject() {
502 // TODO Auto-generated method stub
503 return policyAdapter.getPolicyData();