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.charset.StandardCharsets;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.sql.Connection;
34 import java.sql.DriverManager;
35 import java.sql.ResultSet;
36 import java.sql.SQLException;
37 import java.sql.Statement;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.Iterator;
43 import java.util.StringTokenizer;
44 import java.util.regex.Pattern;
45 import java.util.regex.Matcher;
47 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
48 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
49 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
50 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
51 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
52 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
53 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
54 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
55 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
61 import org.apache.commons.io.FilenameUtils;
62 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
63 import org.openecomp.policy.rest.XACMLRestProperties;
65 import com.att.research.xacml.std.IdentifierImpl;
66 import com.att.research.xacml.util.XACMLProperties;
68 import org.openecomp.policy.common.logging.eelf.MessageCodes;
69 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
70 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
71 import org.openecomp.policy.common.logging.flexlogger.Logger;
73 public class CreateBrmsParamPolicy extends Policy {
77 private static final Logger logger = FlexLogger
78 .getLogger(CreateBrmsParamPolicy.class);
81 * These are the parameters needed for DB access from the PAP
83 private static String papDbDriver = null;
84 private static String papDbUrl = null;
85 private static String papDbUser = null;
86 private static String papDbPassword = null;
88 public CreateBrmsParamPolicy() {
92 public CreateBrmsParamPolicy(PolicyRestAdapter policyAdapter) {
93 this.policyAdapter = policyAdapter;
94 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
98 public String expandConfigBody(String ruleContents,
99 Map<String, String> brmsParamBody
102 Set<String> keySet= new HashSet<String>();
104 Map<String,String> copyMap=new HashMap<>();
105 copyMap.putAll(brmsParamBody);
106 copyMap.put("policyName", policyAdapter.getPolicyName());
107 copyMap.put("policyScope", policyAdapter.getPolicyScope());
108 copyMap.put("policyVersion",policyAdapter.getHighestVersion().toString());
110 //Finding all the keys in the Map data-structure.
111 keySet= copyMap.keySet();
112 Iterator<String> iterator = keySet.iterator();
115 while(iterator.hasNext()) {
116 //Converting the first character of the key into a lower case.
117 String input= iterator.next();
118 String output = Character.toLowerCase(input.charAt(0)) +
119 (input.length() > 1 ? input.substring(1) : "");
120 //Searching for a pattern in the String using the key.
121 p=Pattern.compile("\\$\\{"+output+"\\}");
122 m=p.matcher(ruleContents);
123 //Replacing the value with the inputs provided by the user in the editor.
124 String finalInput = copyMap.get(input);
125 if(finalInput.contains("$")){
126 finalInput = finalInput.replace("$", "\\$");
128 ruleContents=m.replaceAll(finalInput);
130 System.out.println(ruleContents);
134 // Saving the Configurations file at server location for config policy.
135 protected void saveConfigurations(String policyName, String prevPolicyName,
137 final Path gitPath = Paths.get(policyAdapter.getUserGitPath()
139 String policyDir = policyAdapter.getParentPath().toString();
140 int startIndex = policyDir.indexOf(gitPath.toString())
141 + gitPath.toString().length() + 1;
142 policyDir = policyDir.substring(startIndex, policyDir.length());
143 logger.info("print the main domain value" + policyDir);
144 String path = policyDir.replace('\\', '.');
145 if (path.contains("/")) {
146 path = policyDir.replace('/', '.');
147 logger.info("print the path:" + path);
151 String configFileName = getConfigFile(policyName);
153 // Getting the previous policy Config Json file to be used for
154 // updating the dictionary tables
155 if (policyAdapter.isEditPolicy()) {
157 String prevConfigFileName = getConfigFile(prevPolicyName);
160 if (CONFIG_HOME.contains("\\")) {
161 oldFile = new File(CONFIG_HOME + "\\" + path + "."
162 + prevConfigFileName);
164 oldFile = new File(CONFIG_HOME + "/" + path + "."
165 + prevConfigFileName);
168 String filepath = oldFile.toString();
170 String prevJsonBody = readFile(filepath, StandardCharsets.UTF_8);
171 policyAdapter.setPrevJsonBody(prevJsonBody);
174 File configHomeDir = new File(CONFIG_HOME);
175 File[] listOfFiles = configHomeDir.listFiles();
176 if (listOfFiles != null) {
177 for (File eachFile : listOfFiles) {
178 if (eachFile.isFile()) {
179 String fileNameWithoutExtension = FilenameUtils
180 .removeExtension(eachFile.getName());
181 String configFileNameWithoutExtension = FilenameUtils
182 .removeExtension(configFileName);
183 if (fileNameWithoutExtension
184 .equals(configFileNameWithoutExtension)) {
192 catch(IOException e){
197 if (policyName.endsWith(".xml")) {
198 policyName = policyName.substring(0,
199 policyName.lastIndexOf(".xml"));
201 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator
202 + path + "." + policyName + ".txt");
203 String expandedBody=expandConfigBody(ruleBody,policyAdapter.getBrmsParamBody());
204 out.println(expandedBody);
207 } catch (Exception e) {
208 //TODO:EELF Cleanup - Remove logger
209 //logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
210 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving configuration file");
214 // Utility to read json data from the existing file to a string
215 static String readFile(String path, Charset encoding) throws IOException {
217 byte[] encoded = Files.readAllBytes(Paths.get(path));
218 return new String(encoded, encoding);
222 // Here we are adding the extension for the configurations file based on the
223 // config type selection for saving.
224 private String getConfigFile(String filename) {
225 filename = FilenameUtils.removeExtension(filename);
226 if (filename.endsWith(".txt")) {
227 filename = filename.substring(0, filename.length() - 3);
230 filename = filename + ".txt";
234 // Validations for Config form
235 public boolean validateConfigForm() {
237 // Validating mandatory Fields.
244 public Map<String, String> savePolicies() throws Exception {
246 Map<String, String> successMap = new HashMap<String,String>();
247 if(isPolicyExists()){
248 successMap.put("EXISTS", "This Policy already exist on the PAP");
252 if (!isPreparedToSave()) {
255 // Until here we prepared the data and here calling the method to create
257 Path newPolicyPath = null;
258 newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(),
261 Boolean dbIsUpdated = true;
263 successMap = new HashMap<String, String>();
265 successMap = createPolicy(newPolicyPath,
266 getCorrectPolicyDataObject());
268 //TODO:EELF Cleanup - Remove logger
269 //logger.error("Failed to Update the Database Dictionary Tables.");
270 PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
272 // remove the new json file
273 String jsonBody = policyAdapter.getPrevJsonBody();
274 saveConfigurations(policyName, "", jsonBody);
275 successMap.put("error", "DB UPDATE");
278 if (successMap.containsKey("success")) {
279 Path finalPolicyPath = getFinalPolicyPath();
280 policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
285 private String getValueFromDictionary(String templateName){
287 Connection con = null;
292 * Retrieve the property values for db access from the xacml.pap.properties
294 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
295 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
296 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
297 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
299 String ruleTemplate=null;
303 Class.forName(papDbDriver);
304 con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
305 st = con.createStatement();
307 String queryString="select rule from BRMSParamTemplate where param_template_name=\"";
308 queryString=queryString+templateName+"\"";
310 rs = st.executeQuery(queryString);
312 ruleTemplate=rs.getString("rule");
315 }catch (ClassNotFoundException e) {
316 //TODO:EELF Cleanup - Remove logger
317 //logger.error(e.getMessage());
318 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate");
319 System.out.println(e.getMessage());
321 } catch (SQLException e) {
322 //TODO:EELF Cleanup - Remove logger
323 //logger.error(e.getMessage());
324 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate");
325 System.out.println(e.getMessage());
328 if (con!=null) con.close();
329 if (rs!=null) rs.close();
330 if (st!=null) st.close();
331 } catch (Exception ex){}
337 protected Map<String, String> findType(String rule) {
338 Map<String, String> mapFieldType= new HashMap<String,String>();
342 Boolean flag = false;
343 Boolean comment = false;
344 String lines[] = rule.split("\n");
345 for(String line : lines){
346 if (line.isEmpty() || line.startsWith("//")) {
349 if (line.startsWith("/*")) {
353 if (line.contains("//")) {
354 if(!(line.contains("http://") || line.contains("https://"))){
355 line = line.split("\\/\\/")[0];
358 if (line.contains("/*")) {
360 if (line.contains("*/")) {
363 line = line.split("\\/\\*")[0]
364 + line.split("\\*\\/")[1].replace("*/", "");
365 } catch (Exception e) {
366 line = line.split("\\/\\*")[0];
369 line = line.split("\\/\\*")[0];
372 if (line.contains("*/")) {
375 line = line.split("\\*\\/")[1].replace("*/", "");
376 } catch (Exception e) {
384 params = params + line;
386 if (line.contains("declare Params")) {
387 params = params + line;
390 if (line.contains("end") && flag) {
394 params = params.replace("declare Params", "").replace("end", "")
395 .replaceAll("\\s+", "");
396 String[] components = params.split(":");
398 for (int i = 0; i < components.length; i++) {
401 caption = components[i];
403 if(caption.equals("")){
406 String nextComponent = "";
408 nextComponent = components[i + 1];
409 } catch (Exception e) {
410 nextComponent = components[i];
412 //If the type is of type String then we add the UI Item and type to the map.
413 if (nextComponent.startsWith("String")) {
415 mapFieldType.put(caption, type);
416 caption = nextComponent.replace("String", "");
417 } else if (nextComponent.startsWith("int")) {
419 mapFieldType.put(caption, type);
420 caption = nextComponent.replace("int", "");
423 } catch (Exception e) {
424 //TODO:EELF Cleanup - Remove logger
425 //logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
426 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CreateBrmsParamPolicy", "Exception parsing file in findType");
432 // This is the method for preparing the policy for saving. We have broken it
434 // separately because the fully configured policy is used for multiple
437 public boolean prepareToSave() throws Exception {
439 if (isPreparedToSave()) {
440 // we have already done this
445 String policyID = policyAdapter.getPolicyID();
447 if (policyAdapter.isEditPolicy()) {
448 // version = Integer.parseInt(policyAdapter.getVersion()) + 1;
449 version = policyAdapter.getHighestVersion() + 1;
454 // Create the Instance for pojo, PolicyType object is used in
456 if (policyAdapter.getPolicyType().equals("Config")) {
457 PolicyType policyConfig = new PolicyType();
459 policyConfig.setVersion(Integer.toString(version));
460 policyConfig.setPolicyId(policyID);
461 policyConfig.setTarget(new TargetType());
462 policyAdapter.setData(policyConfig);
465 if (policyAdapter.getData() != null) {
467 // Save off everything
468 // making ready all the required elements to generate the action
470 // Get the uniqueness for policy name.
471 String prevPolicyName = null;
472 if (policyAdapter.isEditPolicy()) {
473 prevPolicyName = "Config_BRMS_Param_" + policyAdapter.getPolicyName()
474 + "." + policyAdapter.getHighestVersion() + ".xml";
477 Path newFile = getNextFilename(
478 Paths.get(policyAdapter.getParentPath().toString()),
479 (policyAdapter.getPolicyType() + "_BRMS_Param"),
480 policyAdapter.getPolicyName(), version);
482 if (newFile == null) {
483 //TODO:EELF Cleanup - Remove logger
484 //logger.error("Policy already Exists, cannot create the policy.");
485 PolicyLogger.error("Policy already Exists, cannot create the policy.");
486 setPolicyExists(true);
489 policyName = newFile.getFileName().toString();
492 Map<String,String> ruleAndUIValue= policyAdapter.getBrmsParamBody();
493 String tempateValue= ruleAndUIValue.get("templateName");
494 String valueFromDictionary= getValueFromDictionary(tempateValue);
496 //Get the type of the UI Fields.
497 Map<String,String> typeOfUIField=findType(valueFromDictionary);
498 String generatedRule=null;
504 body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
505 "<$%BRMSParamTemplate=" + tempateValue + "%$> \n */ \n";
506 body = body + valueFromDictionary + "\n";
507 generatedRule = "rule \"Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();";
509 //We first read the map data structure(ruleAndUIValue) received from the PAP-ADMIN
510 //We ignore if the key is "templateName as we are interested only in the UI fields and its value.
511 //We have one more map data structure(typeOfUIField) created by parsing the Drools rule.
512 //From the type of the UI field(String/int) we structure whether to put the "" or not.
513 for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) {
514 if(entry.getKey()!="templateName")
516 for(Map.Entry<String, String> fieldType:typeOfUIField.entrySet())
518 if(fieldType.getKey().equalsIgnoreCase(entry.getKey()))
520 String key = entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1);
521 if(fieldType.getValue()=="String")
524 generatedRule = generatedRule + "\n\t\tparams.set"
526 + entry.getValue() + "\");";
529 generatedRule = generatedRule + "\n\t\tparams.set"
531 + entry.getValue() + ");";
538 generatedRule = generatedRule
539 + "\n\t\tinsert(params);\nend";
540 logger.info("New rule generated with :" + generatedRule);
541 body = body + generatedRule;
542 } catch (Exception e) {
543 //TODO:EELF Cleanup - Remove logger
544 //logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
545 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
548 catch (Exception e) {
549 //TODO:EELF Cleanup - Remove logger
550 //logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
551 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
554 saveConfigurations(policyName,prevPolicyName,body);
556 // Make sure the filename ends with an extension
557 if (policyName.endsWith(".xml") == false) {
558 policyName = policyName + ".xml";
561 PolicyType configPolicy = (PolicyType) policyAdapter.getData();
563 configPolicy.setDescription(policyAdapter.getPolicyDescription());
565 configPolicy.setRuleCombiningAlgId(policyAdapter
566 .getRuleCombiningAlgId());
568 AllOfType allOfOne = new AllOfType();
569 File policyFilePath = new File(policyAdapter.getParentPath()
570 .toString(), policyName);
571 String policyDir = policyFilePath.getParentFile().getName();
572 String fileName = FilenameUtils.removeExtension(policyName);
573 fileName = policyDir + "." + fileName + ".xml";
574 String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
576 if ((name == null) || (name.equals(""))) {
577 name = fileName.substring(fileName.lastIndexOf("/") + 1,
580 allOfOne.getMatch().add(createMatch("PolicyName", name));
583 AllOfType allOf = new AllOfType();
585 // Match for ECOMPName
586 allOf.getMatch().add(
587 createMatch("ECOMPName", policyAdapter.getEcompName()));
588 allOf.getMatch().add(
589 createMatch("ConfigName", policyAdapter.getConfigName()));
590 // Match for riskType
591 allOf.getMatch().add(
592 createDynamicMatch("RiskType", policyAdapter.getRiskType()));
593 // Match for riskLevel
594 allOf.getMatch().add(
595 createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
596 // Match for riskguard
597 allOf.getMatch().add(
598 createDynamicMatch("guard", policyAdapter.getGuard()));
600 allOf.getMatch().add(
601 createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
602 AnyOfType anyOf = new AnyOfType();
603 anyOf.getAllOf().add(allOfOne);
604 anyOf.getAllOf().add(allOf);
606 TargetType target = new TargetType();
607 ((TargetType) target).getAnyOf().add(anyOf);
609 // Adding the target to the policy element
610 configPolicy.setTarget((TargetType) target);
612 RuleType rule = new RuleType();
613 rule.setRuleId(policyAdapter.getRuleID());
615 rule.setEffect(EffectType.PERMIT);
617 // Create Target in Rule
618 AllOfType allOfInRule = new AllOfType();
620 // Creating match for ACCESS in rule target
621 MatchType accessMatch = new MatchType();
622 AttributeValueType accessAttributeValue = new AttributeValueType();
623 accessAttributeValue.setDataType(STRING_DATATYPE);
624 accessAttributeValue.getContent().add("ACCESS");
625 accessMatch.setAttributeValue(accessAttributeValue);
626 AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
627 URI accessURI = null;
629 accessURI = new URI(ACTION_ID);
630 } catch (URISyntaxException e) {
631 //TODO:EELF Cleanup - Remove logger
632 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
633 //+ e.getStackTrace());
634 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", "Exception creating ACCESS URI");
636 accessAttributeDesignator.setCategory(CATEGORY_ACTION);
637 accessAttributeDesignator.setDataType(STRING_DATATYPE);
638 accessAttributeDesignator.setAttributeId(new IdentifierImpl(
639 accessURI).stringValue());
640 accessMatch.setAttributeDesignator(accessAttributeDesignator);
641 accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
643 // Creating Config Match in rule Target
644 MatchType configMatch = new MatchType();
645 AttributeValueType configAttributeValue = new AttributeValueType();
646 configAttributeValue.setDataType(STRING_DATATYPE);
648 configAttributeValue.getContent().add("Config");
650 configMatch.setAttributeValue(configAttributeValue);
651 AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
652 URI configURI = null;
654 configURI = new URI(RESOURCE_ID);
655 } catch (URISyntaxException e) {
656 //TODO:EELF Cleanup - Remove logger
657 //logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE
658 //+ e.getStackTrace());
659 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", "Exception creating Config URI");
662 configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
663 configAttributeDesignator.setDataType(STRING_DATATYPE);
664 configAttributeDesignator.setAttributeId(new IdentifierImpl(
665 configURI).stringValue());
666 configMatch.setAttributeDesignator(configAttributeDesignator);
667 configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
669 allOfInRule.getMatch().add(accessMatch);
670 allOfInRule.getMatch().add(configMatch);
672 AnyOfType anyOfInRule = new AnyOfType();
673 anyOfInRule.getAllOf().add(allOfInRule);
675 TargetType targetInRule = new TargetType();
676 targetInRule.getAnyOf().add(anyOfInRule);
678 rule.setTarget(targetInRule);
679 rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
682 .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
684 policyAdapter.setPolicyData(configPolicy);
687 //TODO:EELF Cleanup - Remove logger
688 //logger.error("Unsupported data object."
689 //+ policyAdapter.getData().getClass().getCanonicalName());
690 PolicyLogger.error("Unsupported data object."
691 + policyAdapter.getData().getClass().getCanonicalName());
693 setPreparedToSave(true);
697 // Data required for Advice part is setting here.
698 private AdviceExpressionsType getAdviceExpressions(int version,
701 //Policy Config ID Assignment
702 AdviceExpressionsType advices = new AdviceExpressionsType();
703 AdviceExpressionType advice = new AdviceExpressionType();
704 advice.setAdviceId("BRMSPARAMID");
705 advice.setAppliesTo(EffectType.PERMIT);
707 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
708 assignment1.setAttributeId("type");
709 assignment1.setCategory(CATEGORY_RESOURCE);
710 assignment1.setIssuer("");
711 AttributeValueType configNameAttributeValue = new AttributeValueType();
712 configNameAttributeValue.setDataType(STRING_DATATYPE);
713 configNameAttributeValue.getContent().add("Configuration");
714 assignment1.setExpression(new ObjectFactory()
715 .createAttributeValue(configNameAttributeValue));
716 advice.getAttributeAssignmentExpression().add(assignment1);
718 // For Config file Url if configurations are provided.
720 final Path gitPath = Paths.get(policyAdapter.getUserGitPath()
722 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
723 assignment2.setAttributeId("URLID");
724 assignment2.setCategory(CATEGORY_RESOURCE);
725 assignment2.setIssuer("");
726 AttributeValueType AttributeValue = new AttributeValueType();
727 AttributeValue.setDataType(URI_DATATYPE);
728 String policyDir1 = policyAdapter.getParentPath().toString();
729 int startIndex1 = policyDir1.indexOf(gitPath.toString())
730 + gitPath.toString().length() + 1;
731 policyDir1 = policyDir1.substring(startIndex1, policyDir1.length());
732 logger.info("print the main domain value" + policyDir1);
733 String path = policyDir1.replace('\\', '.');
734 if (path.contains("/")) {
735 path = policyDir1.replace('/', '.');
736 logger.info("print the path:" + path);
738 String content = CONFIG_URL + "/Config/" + path + "."
739 + getConfigFile(policyName);
741 AttributeValue.getContent().add(content);
742 assignment2.setExpression(new ObjectFactory()
743 .createAttributeValue(AttributeValue));
744 advice.getAttributeAssignmentExpression().add(assignment2);
746 // Policy Name Assignment
747 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
748 assignment3.setAttributeId("PolicyName");
749 assignment3.setCategory(CATEGORY_RESOURCE);
750 assignment3.setIssuer("");
751 AttributeValueType attributeValue3 = new AttributeValueType();
752 attributeValue3.setDataType(STRING_DATATYPE);
753 String policyDir = policyAdapter.getParentPath().toString();
754 int startIndex = policyDir.indexOf(gitPath.toString())
755 + gitPath.toString().length() + 1;
756 policyDir = policyDir.substring(startIndex, policyDir.length());
757 StringTokenizer tokenizer = null;
758 StringBuffer buffer = new StringBuffer();
759 if (policyDir.contains("\\")) {
760 tokenizer = new StringTokenizer(policyDir, "\\");
762 tokenizer = new StringTokenizer(policyDir, "/");
764 if (tokenizer != null) {
765 while (tokenizer.hasMoreElements()) {
766 String value = tokenizer.nextToken();
767 buffer.append(value);
771 fileName = FilenameUtils.removeExtension(fileName);
772 fileName = buffer.toString() + fileName + ".xml";
773 System.out.println(fileName);
774 String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
776 if ((name == null) || (name.equals(""))) {
777 name = fileName.substring(fileName.lastIndexOf("/") + 1,
780 System.out.println(name);
781 attributeValue3.getContent().add(name);
782 assignment3.setExpression(new ObjectFactory()
783 .createAttributeValue(attributeValue3));
784 advice.getAttributeAssignmentExpression().add(assignment3);
786 // Version Number Assignment
787 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
788 assignment4.setAttributeId("VersionNumber");
789 assignment4.setCategory(CATEGORY_RESOURCE);
790 assignment4.setIssuer("");
791 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
792 configNameAttributeValue4.setDataType(STRING_DATATYPE);
793 configNameAttributeValue4.getContent().add(Integer.toString(version));
794 assignment4.setExpression(new ObjectFactory()
795 .createAttributeValue(configNameAttributeValue4));
796 advice.getAttributeAssignmentExpression().add(assignment4);
798 // Ecomp Name Assignment
799 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
800 assignment5.setAttributeId("matching:" + this.ECOMPID);
801 assignment5.setCategory(CATEGORY_RESOURCE);
802 assignment5.setIssuer("");
803 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
804 configNameAttributeValue5.setDataType(STRING_DATATYPE);
805 configNameAttributeValue5.getContent().add(policyAdapter.getEcompName());
806 assignment5.setExpression(new ObjectFactory()
807 .createAttributeValue(configNameAttributeValue5));
808 advice.getAttributeAssignmentExpression().add(assignment5);
811 //Config Name Assignment
812 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
813 assignment6.setAttributeId("matching:" + this.CONFIGID);
814 assignment6.setCategory(CATEGORY_RESOURCE);
815 assignment6.setIssuer("");
816 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
817 configNameAttributeValue6.setDataType(STRING_DATATYPE);
818 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
819 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
820 advice.getAttributeAssignmentExpression().add(assignment6);
822 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
823 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
824 String key = keyField;
825 String value = dynamicFieldConfigAttributes.get(key);
826 AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
827 assignment7.setAttributeId("key:" + key);
828 assignment7.setCategory(CATEGORY_RESOURCE);
829 assignment7.setIssuer("");
831 AttributeValueType configNameAttributeValue7 = new AttributeValueType();
832 configNameAttributeValue7.setDataType(STRING_DATATYPE);
833 configNameAttributeValue7.getContent().add(value);
834 assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
836 advice.getAttributeAssignmentExpression().add(assignment7);
840 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
841 assignment8.setAttributeId("RiskType");
842 assignment8.setCategory(CATEGORY_RESOURCE);
843 assignment8.setIssuer("");
845 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
846 configNameAttributeValue8.setDataType(STRING_DATATYPE);
847 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
848 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
850 advice.getAttributeAssignmentExpression().add(assignment8);
852 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
853 assignment9.setAttributeId("RiskLevel");
854 assignment9.setCategory(CATEGORY_RESOURCE);
855 assignment9.setIssuer("");
857 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
858 configNameAttributeValue9.setDataType(STRING_DATATYPE);
859 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
860 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
862 advice.getAttributeAssignmentExpression().add(assignment9);
864 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
865 assignment10.setAttributeId("guard");
866 assignment10.setCategory(CATEGORY_RESOURCE);
867 assignment10.setIssuer("");
869 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
870 configNameAttributeValue10.setDataType(STRING_DATATYPE);
871 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
872 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
874 advice.getAttributeAssignmentExpression().add(assignment10);
876 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
877 assignment11.setAttributeId("TTLDate");
878 assignment11.setCategory(CATEGORY_RESOURCE);
879 assignment11.setIssuer("");
881 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
882 configNameAttributeValue11.setDataType(STRING_DATATYPE);
883 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
884 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
886 advice.getAttributeAssignmentExpression().add(assignment11);
888 advices.getAdviceExpression().add(advice);
893 public Object getCorrectPolicyDataObject() {
894 return policyAdapter.getData();