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.file.Path;
29 import java.nio.file.Paths;
30 import java.util.HashMap;
32 import java.util.StringTokenizer;
34 import javax.json.stream.JsonGenerationException;
36 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
37 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
38 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
39 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
40 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
41 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
42 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
43 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
44 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
45 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
46 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
50 import org.apache.commons.io.FilenameUtils;
51 import org.apache.commons.logging.Log;
52 import org.apache.commons.logging.LogFactory;
53 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
55 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
56 import com.att.research.xacml.std.IdentifierImpl;
58 import org.openecomp.policy.common.logging.eelf.MessageCodes;
59 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
60 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
61 import org.openecomp.policy.common.logging.flexlogger.Logger;
63 public class MicroServiceConfigPolicy extends Policy {
68 private static final Logger logger = FlexLogger.getLogger(ConfigPolicy.class);
70 public MicroServiceConfigPolicy() {
74 public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){
75 this.policyAdapter = policyAdapter;
78 //save configuration of the policy based on the policyname
79 private void saveConfigurations(String policyName, String prevPolicyName, String jsonBody) {
80 String domain = getParentPathSubScopeDir();
81 String path = domain.replace('\\', '.');
82 if(path.contains("/")){
83 path = domain.replace('/', '.');
84 logger.info("print the path:" +path);
90 } catch (Exception e) {
94 System.out.println(body);
95 if(policyName.endsWith(".xml")){
96 policyName = policyName.substring(0, policyName.lastIndexOf(".xml"));
98 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator+path + "."+ policyName +".json");
102 } catch (JsonGenerationException e) {
104 } catch (IOException e) {
110 //getting the policy name and setting to configuration on adding .json
111 private String getConfigFile(String filename) {
112 filename = FilenameUtils.removeExtension(filename);
113 if (filename.endsWith(".xml")) {
114 filename = filename.substring(0, filename.length() - 4);
116 filename = filename +".json";
121 public Map<String, String> savePolicies() throws Exception {
123 Map<String, String> successMap = new HashMap<String,String>();
124 if(isPolicyExists()){
125 successMap.put("EXISTS", "This Policy already exist on the PAP");
129 if(!isPreparedToSave()){
130 //Prep and configure the policy for saving
134 // Until here we prepared the data and here calling the method to create xml.
135 Path newPolicyPath = null;
136 newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(), policyName);
137 successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject() );
138 if (successMap.containsKey("success")) {
139 Path finalPolicyPath = getFinalPolicyPath();
140 policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
145 //This is the method for preparing the policy for saving. We have broken it out
146 //separately because the fully configured policy is used for multiple things
148 public boolean prepareToSave() throws Exception{
150 if(isPreparedToSave()){
151 //we have already done this
156 String policyID = policyAdapter.getPolicyID();
158 if (policyAdapter.isEditPolicy()) {
159 version = policyAdapter.getHighestVersion() + 1;
164 // Create the Instance for pojo, PolicyType object is used in marshalling.
165 if (policyAdapter.getPolicyType().equals("Config")) {
166 PolicyType policyConfig = new PolicyType();
168 policyConfig.setVersion(Integer.toString(version));
169 policyConfig.setPolicyId(policyID);
170 policyConfig.setTarget(new TargetType());
171 policyAdapter.setData(policyConfig);
174 if (policyAdapter.getData() != null) {
176 // Save off everything
177 // making ready all the required elements to generate the action policy xml.
178 // Get the uniqueness for policy name.
179 String prevPolicyName = null;
180 if(policyAdapter.isEditPolicy()){
181 prevPolicyName = "Config_MS_" + policyAdapter.getPolicyName() + "." + policyAdapter.getHighestVersion() + ".xml";
184 Path newFile = this.getNextLoopFilename(Paths.get(policyAdapter.getParentPath()), policyAdapter.getPolicyType(),
185 policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), version);
187 if (newFile == null) {
188 //TODO:EELF Cleanup - Remove logger
189 //logger.error("Policy already Exists, cannot create the policy.");
190 PolicyLogger.error("Policy 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());
231 // Match for policyName
232 allOfOne.getMatch().add(createMatch("PolicyName", name));
234 AllOfType allOf = new AllOfType();
236 // Adding the matches to AllOfType element Match for Ecomp
237 allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName()));
238 // Match for ConfigName
239 allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
241 allOf.getMatch().add(createDynamicMatch("service", policyAdapter.getServiceType()));
243 allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid()));
244 // Match for location
245 allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation()));
246 // Match for riskType
247 allOf.getMatch().add(
248 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
249 // Match for riskLevel
250 allOf.getMatch().add(
251 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
252 // Match for riskguard
253 allOf.getMatch().add(
254 createDynamicMatch("guard", policyAdapter.getGuard()));
256 allOf.getMatch().add(
257 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
259 AnyOfType anyOf = new AnyOfType();
260 anyOf.getAllOf().add(allOfOne);
261 anyOf.getAllOf().add(allOf);
263 TargetType target = new TargetType();
264 ((TargetType) target).getAnyOf().add(anyOf);
266 // Adding the target to the policy element
267 configPolicy.setTarget((TargetType) target);
269 RuleType rule = new RuleType();
270 rule.setRuleId(policyAdapter.getRuleID());
272 rule.setEffect(EffectType.PERMIT);
274 // Create Target in Rule
275 AllOfType allOfInRule = new AllOfType();
277 // Creating match for ACCESS in rule target
278 MatchType accessMatch = new MatchType();
279 AttributeValueType accessAttributeValue = new AttributeValueType();
280 accessAttributeValue.setDataType(STRING_DATATYPE);
281 accessAttributeValue.getContent().add("ACCESS");
282 accessMatch.setAttributeValue(accessAttributeValue);
283 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
284 URI accessURI = null;
286 accessURI = new URI(ACTION_ID);
287 } catch (URISyntaxException e) {
288 //TODO:EELF Cleanup - Remove logger
289 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
290 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI");
292 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
293 accessAttributeDesignator.setDataType(STRING_DATATYPE);
294 accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue());
295 accessMatch.setAttributeDesignator(accessAttributeDesignator);
296 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
298 // Creating Config Match in rule Target
299 MatchType configMatch = new MatchType();
300 AttributeValueType configAttributeValue = new AttributeValueType();
301 configAttributeValue.setDataType(STRING_DATATYPE);
302 configAttributeValue.getContent().add("Config");
303 configMatch.setAttributeValue(configAttributeValue);
304 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
305 URI configURI = null;
307 configURI = new URI(RESOURCE_ID);
308 } catch (URISyntaxException e) {
309 //TODO:EELF Cleanup - Remove logger
310 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getStackTrace());
311 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI");
313 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
314 configAttributeDesignator.setDataType(STRING_DATATYPE);
315 configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
316 configMatch.setAttributeDesignator(configAttributeDesignator);
317 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
319 allOfInRule.getMatch().add(accessMatch);
320 allOfInRule.getMatch().add(configMatch);
322 AnyOfType anyOfInRule = new AnyOfType();
323 anyOfInRule.getAllOf().add(allOfInRule);
325 TargetType targetInRule = new TargetType();
326 targetInRule.getAnyOf().add(anyOfInRule);
328 rule.setTarget(targetInRule);
329 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
331 configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule);
332 policyAdapter.setPolicyData(configPolicy);
335 //TODO:EELF Cleanup - Remove logger
336 //logger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
337 PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName());
339 setPreparedToSave(true);
343 // Data required for Advice part is setting here.
344 private AdviceExpressionsType getAdviceExpressions(int version, String fileName) {
345 AdviceExpressionsType advices = new AdviceExpressionsType();
346 AdviceExpressionType advice = new AdviceExpressionType();
347 advice.setAdviceId("MSID");
348 advice.setAppliesTo(EffectType.PERMIT);
350 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
351 assignment1.setAttributeId("type");
352 assignment1.setCategory(CATEGORY_RESOURCE);
353 assignment1.setIssuer("");
355 AttributeValueType configNameAttributeValue = new AttributeValueType();
356 configNameAttributeValue.setDataType(STRING_DATATYPE);
357 configNameAttributeValue.getContent().add("Configuration");
358 assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue));
360 advice.getAttributeAssignmentExpression().add(assignment1);
361 final Path gitPath = Paths.get(policyAdapter.getUserGitPath().toString());
362 // For Config file Url if configurations are provided.
363 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
364 assignment2.setAttributeId("URLID");
365 assignment2.setCategory(CATEGORY_RESOURCE);
366 assignment2.setIssuer("");
368 AttributeValueType AttributeValue = new AttributeValueType();
369 AttributeValue.setDataType(URI_DATATYPE);
370 String policyDir1 = policyAdapter.getParentPath().toString();
371 int startIndex1 = policyDir1.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
372 policyDir1 = policyDir1.substring(startIndex1, policyDir1.length());
373 logger.info("print the main domain value"+policyDir1);
374 String path = policyDir1.replace('\\', '.');
375 if(path.contains("/")){
376 path = policyDir1.replace('/', '.');
377 logger.info("print the path:" +path);
379 String content = CONFIG_URL +"/Config/" + path + "." + getConfigFile(policyName);
380 System.out.println("URL value :" + content);
381 AttributeValue.getContent().add(content);
382 assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue));
384 advice.getAttributeAssignmentExpression().add(assignment2);
385 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
386 assignment3.setAttributeId("PolicyName");
387 assignment3.setCategory(CATEGORY_RESOURCE);
388 assignment3.setIssuer("");
390 AttributeValueType attributeValue3 = new AttributeValueType();
391 attributeValue3.setDataType(STRING_DATATYPE);
392 String policyDir = policyAdapter.getParentPath().toString();
393 int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1;
394 policyDir = policyDir.substring(startIndex, policyDir.length());
395 StringTokenizer tokenizer = null;
396 StringBuffer buffer = new StringBuffer();
397 if (policyDir.contains("\\")) {
398 tokenizer = new StringTokenizer(policyDir, "\\");
400 tokenizer = new StringTokenizer(policyDir, "/");
402 if (tokenizer != null) {
403 while (tokenizer.hasMoreElements()) {
404 String value = tokenizer.nextToken();
405 buffer.append(value);
409 fileName = FilenameUtils.removeExtension(fileName);
410 fileName = buffer.toString() + fileName + ".xml";
411 String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
412 if ((name == null) || (name.equals(""))) {
413 name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length());
415 attributeValue3.getContent().add(name);
416 assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3));
417 advice.getAttributeAssignmentExpression().add(assignment3);
419 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
420 assignment4.setAttributeId("VersionNumber");
421 assignment4.setCategory(CATEGORY_RESOURCE);
422 assignment4.setIssuer("");
424 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
425 configNameAttributeValue4.setDataType(STRING_DATATYPE);
426 configNameAttributeValue4.getContent().add(Integer.toString(version));
427 assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4));
429 advice.getAttributeAssignmentExpression().add(assignment4);
431 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
432 assignment5.setAttributeId("matching:" + this.ECOMPID);
433 assignment5.setCategory(CATEGORY_RESOURCE);
434 assignment5.setIssuer("");
436 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
437 configNameAttributeValue5.setDataType(STRING_DATATYPE);
438 configNameAttributeValue5.getContent().add(policyAdapter.getEcompName());
439 assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5));
441 advice.getAttributeAssignmentExpression().add(assignment5);
443 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
444 assignment6.setAttributeId("matching:" + this.CONFIGID);
445 assignment6.setCategory(CATEGORY_RESOURCE);
446 assignment6.setIssuer("");
448 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
449 configNameAttributeValue6.setDataType(STRING_DATATYPE);
450 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
451 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
453 advice.getAttributeAssignmentExpression().add(assignment6);
454 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
455 assignment7.setAttributeId("matching:service");
456 assignment7.setCategory(CATEGORY_RESOURCE);
457 assignment7.setIssuer("");
459 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
460 configNameAttributeValue7.setDataType(STRING_DATATYPE);
461 configNameAttributeValue7.getContent().add(policyAdapter.getServiceType());
462 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
464 advice.getAttributeAssignmentExpression().add(assignment7);
466 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
467 assignment8.setAttributeId("matching:uuid");
468 assignment8.setCategory(CATEGORY_RESOURCE);
469 assignment8.setIssuer("");
471 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
472 configNameAttributeValue8.setDataType(STRING_DATATYPE);
473 configNameAttributeValue8.getContent().add(policyAdapter.getUuid());
474 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
476 advice.getAttributeAssignmentExpression().add(assignment8);
478 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
479 assignment9.setAttributeId("matching:Location");
480 assignment9.setCategory(CATEGORY_RESOURCE);
481 assignment9.setIssuer("");
483 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
484 configNameAttributeValue9.setDataType(STRING_DATATYPE);
485 configNameAttributeValue9.getContent().add(policyAdapter.getLocation());
486 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
488 advice.getAttributeAssignmentExpression().add(assignment9);
490 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
491 assignment10.setAttributeId("Priority");
492 assignment10.setCategory(CATEGORY_RESOURCE);
493 assignment10.setIssuer("");
495 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
496 configNameAttributeValue10.setDataType(STRING_DATATYPE);
497 configNameAttributeValue10.getContent().add(policyAdapter.getPriority());
498 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
500 advice.getAttributeAssignmentExpression().add(assignment10);
503 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
504 assignment11.setAttributeId("RiskType");
505 assignment11.setCategory(CATEGORY_RESOURCE);
506 assignment11.setIssuer("");
508 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
509 configNameAttributeValue11.setDataType(STRING_DATATYPE);
510 configNameAttributeValue11.getContent().add(policyAdapter.getRiskType());
511 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
513 advice.getAttributeAssignmentExpression().add(assignment11);
515 AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
516 assignment12.setAttributeId("RiskLevel");
517 assignment12.setCategory(CATEGORY_RESOURCE);
518 assignment12.setIssuer("");
520 AttributeValueType configNameAttributeValue12 = new AttributeValueType();
521 configNameAttributeValue12.setDataType(STRING_DATATYPE);
522 configNameAttributeValue12.getContent().add(policyAdapter.getRiskLevel());
523 assignment12.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue12));
525 advice.getAttributeAssignmentExpression().add(assignment12);
527 AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
528 assignment13.setAttributeId("guard");
529 assignment13.setCategory(CATEGORY_RESOURCE);
530 assignment13.setIssuer("");
532 AttributeValueType configNameAttributeValue13 = new AttributeValueType();
533 configNameAttributeValue13.setDataType(STRING_DATATYPE);
534 configNameAttributeValue13.getContent().add(policyAdapter.getRiskLevel());
535 assignment13.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue13));
537 advice.getAttributeAssignmentExpression().add(assignment13);
539 AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
540 assignment14.setAttributeId("TTLDate");
541 assignment14.setCategory(CATEGORY_RESOURCE);
542 assignment14.setIssuer("");
544 AttributeValueType configNameAttributeValue14 = new AttributeValueType();
545 configNameAttributeValue14.setDataType(STRING_DATATYPE);
546 configNameAttributeValue14.getContent().add(policyAdapter.getTtlDate());
547 assignment14.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue14));
549 advice.getAttributeAssignmentExpression().add(assignment14);
551 advices.getAdviceExpression().add(advice);
556 public Object getCorrectPolicyDataObject() {
557 return policyAdapter.getPolicyData();