Initial OpenECOMP policy/engine commit
[policy/engine.git] / ECOMP-PAP-REST / src / main / java / org / openecomp / policy / pap / xacml / rest / components / CreateBrmsParamPolicy.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP-PAP-REST
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.policy.pap.xacml.rest.components;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.io.PrintWriter;
26 import java.net.URI;
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;
41 import java.util.Map;
42 import java.util.Set;
43 import java.util.StringTokenizer;
44 import java.util.regex.Pattern;
45 import java.util.regex.Matcher; 
46
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;
60
61 import org.apache.commons.io.FilenameUtils;
62 import org.openecomp.policy.pap.xacml.rest.adapters.PolicyRestAdapter;
63 import org.openecomp.policy.rest.XACMLRestProperties;
64
65 import com.att.research.xacml.std.IdentifierImpl;
66 import com.att.research.xacml.util.XACMLProperties;
67
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; 
72
73 public class CreateBrmsParamPolicy extends Policy {
74         /**
75          * Config Fields
76          */
77         private static final Logger logger = FlexLogger
78                         .getLogger(CreateBrmsParamPolicy.class);
79
80         /*
81          * These are the parameters needed for DB access from the PAP
82          */
83         private static String papDbDriver = null;
84         private static String papDbUrl = null;
85         private static String papDbUser = null;
86         private static String papDbPassword = null;
87
88         public CreateBrmsParamPolicy() {
89                 super();
90         }
91
92         public CreateBrmsParamPolicy(PolicyRestAdapter policyAdapter) {
93                 this.policyAdapter = policyAdapter;
94                 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
95
96         }
97         
98         public String expandConfigBody(String ruleContents,  
99                                                                                 Map<String, String> brmsParamBody
100                                                                                   ) { 
101                          
102                         Set<String> keySet= new HashSet<String>();
103                         
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());
109                         
110                         //Finding all the keys in the Map data-structure.
111                         keySet= copyMap.keySet();
112                         Iterator<String> iterator = keySet.iterator(); 
113                         Pattern p;
114                         Matcher m;
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("$", "\\$");
127                                 }
128                                 ruleContents=m.replaceAll(finalInput);
129                         }
130                         System.out.println(ruleContents);
131                         return ruleContents; 
132         } 
133                          
134         // Saving the Configurations file at server location for config policy.
135         protected void saveConfigurations(String policyName, String prevPolicyName,
136                         String ruleBody) {
137                 final Path gitPath = Paths.get(policyAdapter.getUserGitPath()
138                                 .toString());
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);
148                 }
149
150                 
151                         String configFileName = getConfigFile(policyName);
152         try{
153                         // Getting the previous policy Config Json file to be used for
154                         // updating the dictionary tables
155                         if (policyAdapter.isEditPolicy()) {
156
157                                 String prevConfigFileName = getConfigFile(prevPolicyName);
158
159                                 File oldFile;
160                                 if (CONFIG_HOME.contains("\\")) {
161                                         oldFile = new File(CONFIG_HOME + "\\" + path + "."
162                                                         + prevConfigFileName);
163                                 } else {
164                                         oldFile = new File(CONFIG_HOME + "/" + path + "."
165                                                         + prevConfigFileName);
166                                 }
167
168                                 String filepath = oldFile.toString();
169
170                                 String prevJsonBody = readFile(filepath, StandardCharsets.UTF_8);
171                                 policyAdapter.setPrevJsonBody(prevJsonBody);
172                         }
173
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)) {
185                                                         // delete the file
186                                                         eachFile.delete();
187                                                 }
188                                         }
189                                 }
190                         }
191         }
192         catch(IOException e){
193                 
194         }
195                         try {
196                                 
197                                 if (policyName.endsWith(".xml")) {
198                                         policyName = policyName.substring(0,
199                                                         policyName.lastIndexOf(".xml"));
200                                 }
201                                 PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator
202                                                 + path + "." + policyName + ".txt");
203                                 String expandedBody=expandConfigBody(ruleBody,policyAdapter.getBrmsParamBody());
204                                 out.println(expandedBody);
205                                 out.close();
206
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");
211                         }
212         }
213
214         // Utility to read json data from the existing file to a string
215         static String readFile(String path, Charset encoding) throws IOException {
216
217                 byte[] encoded = Files.readAllBytes(Paths.get(path));
218                 return new String(encoded, encoding);
219
220         }
221
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);
228                 }
229
230                 filename = filename + ".txt";
231                 return filename;
232         }
233
234         // Validations for Config form
235         public boolean validateConfigForm() {
236
237                 // Validating mandatory Fields.
238                 isValidForm = true;
239                 return isValidForm;
240
241         }
242
243         @Override
244         public Map<String, String> savePolicies() throws Exception {
245                 
246                 Map<String, String> successMap = new HashMap<String,String>();
247                 if(isPolicyExists()){
248                         successMap.put("EXISTS", "This Policy already exist on the PAP");
249                         return successMap;
250                 }
251                 
252                 if (!isPreparedToSave()) {
253                         prepareToSave();
254                 }
255                 // Until here we prepared the data and here calling the method to create
256                 // xml.
257                 Path newPolicyPath = null;
258                 newPolicyPath = Paths.get(policyAdapter.getParentPath().toString(),
259                                 policyName);
260                 
261                 Boolean dbIsUpdated = true;
262
263                 successMap = new HashMap<String, String>();
264                 if (dbIsUpdated) {
265                         successMap = createPolicy(newPolicyPath,
266                                         getCorrectPolicyDataObject());
267                 } else {
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.");
271
272                         // remove the new json file
273                         String jsonBody = policyAdapter.getPrevJsonBody();
274                         saveConfigurations(policyName, "", jsonBody);
275                         successMap.put("error", "DB UPDATE");
276                 }
277
278                 if (successMap.containsKey("success")) {
279                         Path finalPolicyPath = getFinalPolicyPath();
280                         policyAdapter.setFinalPolicyPath(finalPolicyPath.toString());
281                 }
282                 return successMap;
283         }
284         
285         private String getValueFromDictionary(String templateName){
286                 
287                 Connection con = null;
288                 Statement st = null;
289                 ResultSet rs = null;
290                 
291                 /*
292                  * Retrieve the property values for db access from the xacml.pap.properties
293                  */
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);
298                 
299                 String ruleTemplate=null;
300                 
301                 try {
302                         //Get DB Connection
303                         Class.forName(papDbDriver);
304                         con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
305                         st = con.createStatement();
306                         
307                         String queryString="select rule from BRMSParamTemplate where param_template_name=\"";
308                         queryString=queryString+templateName+"\"";
309                         
310                         rs = st.executeQuery(queryString);
311                         if(rs.next()){
312                                 ruleTemplate=rs.getString("rule");
313                         }
314                         rs.close();
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());
320
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());
326                 } finally {
327                         try{
328                                 if (con!=null) con.close();
329                                 if (rs!=null) rs.close();
330                                 if (st!=null) st.close();
331                         } catch (Exception ex){}
332                 }
333                 return ruleTemplate;
334                 
335         }
336         
337         protected Map<String, String> findType(String rule) {
338                 Map<String, String> mapFieldType= new HashMap<String,String>();
339                 if(rule!=null){
340                         try {
341                                 String params = "";
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("//")) {
347                                                 continue;
348                                         }
349                                         if (line.startsWith("/*")) {
350                                                 comment = true;
351                                                 continue;
352                                         }
353                                         if (line.contains("//")) {
354                                                 if(!(line.contains("http://") || line.contains("https://"))){
355                                                         line = line.split("\\/\\/")[0];
356                                                 }
357                                         }
358                                         if (line.contains("/*")) {
359                                                 comment = true;
360                                                 if (line.contains("*/")) {
361                                                         try {
362                                                                 comment = false;
363                                                                 line = line.split("\\/\\*")[0]
364                                                                                 + line.split("\\*\\/")[1].replace("*/", "");
365                                                         } catch (Exception e) {
366                                                                 line = line.split("\\/\\*")[0];
367                                                         }
368                                                 } else {
369                                                         line = line.split("\\/\\*")[0];
370                                                 }
371                                         }
372                                         if (line.contains("*/")) {
373                                                 comment = false;
374                                                 try {
375                                                         line = line.split("\\*\\/")[1].replace("*/", "");
376                                                 } catch (Exception e) {
377                                                         line = "";
378                                                 }
379                                         }
380                                         if (comment) {
381                                                 continue;
382                                         }
383                                         if (flag) {
384                                                 params = params + line;
385                                         }
386                                         if (line.contains("declare Params")) {
387                                                 params = params + line;
388                                                 flag = true;
389                                         }
390                                         if (line.contains("end") && flag) {
391                                                 break;
392                                         }
393                                 }
394                                 params = params.replace("declare Params", "").replace("end", "")
395                                                 .replaceAll("\\s+", "");
396                                 String[] components = params.split(":");
397                                 String caption = "";
398                                 for (int i = 0; i < components.length; i++) {
399                                         String type = "";
400                                         if (i == 0) {
401                                                 caption = components[i];
402                                         }
403                                         if(caption.equals("")){
404                                                 break;
405                                         }
406                                         String nextComponent = "";
407                                         try {
408                                                 nextComponent = components[i + 1];
409                                         } catch (Exception e) {
410                                                 nextComponent = components[i];
411                                         }
412                                         //If the type is of type String then we add the UI Item and type to the map. 
413                                         if (nextComponent.startsWith("String")) {
414                                                 type = "String";
415                                                 mapFieldType.put(caption, type);
416                                                 caption = nextComponent.replace("String", "");
417                                         } else if (nextComponent.startsWith("int")) {
418                                                 type = "int";
419                                                 mapFieldType.put(caption, type);
420                                                 caption = nextComponent.replace("int", "");
421                                         }
422                                 }
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");
427                         }
428                 }
429                 return mapFieldType;
430         }
431         
432         // This is the method for preparing the policy for saving. We have broken it
433         // out
434         // separately because the fully configured policy is used for multiple
435         // things
436         @Override
437         public boolean prepareToSave() throws Exception {
438                 
439                 if (isPreparedToSave()) {
440                         // we have already done this
441                         return true;
442                 }
443
444                 int version = 0;
445                 String policyID = policyAdapter.getPolicyID();
446
447                 if (policyAdapter.isEditPolicy()) {
448                         // version = Integer.parseInt(policyAdapter.getVersion()) + 1;
449                         version = policyAdapter.getHighestVersion() + 1;
450                 } else {
451                         version = 1;
452                 }
453
454                 // Create the Instance for pojo, PolicyType object is used in
455                 // marshalling.
456                 if (policyAdapter.getPolicyType().equals("Config")) {
457                         PolicyType policyConfig = new PolicyType();
458
459                         policyConfig.setVersion(Integer.toString(version));
460                         policyConfig.setPolicyId(policyID);
461                         policyConfig.setTarget(new TargetType());
462                         policyAdapter.setData(policyConfig);
463                 }
464
465                 if (policyAdapter.getData() != null) {
466
467                         // Save off everything
468                         // making ready all the required elements to generate the action
469                         // policy xml.
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";
475                         }
476
477                         Path newFile = getNextFilename(
478                                         Paths.get(policyAdapter.getParentPath().toString()),
479                                         (policyAdapter.getPolicyType() + "_BRMS_Param"),
480                                         policyAdapter.getPolicyName(), version);
481
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);
487                                 return false;                   
488                         }
489                         policyName = newFile.getFileName().toString();
490                         
491                                 
492                         Map<String,String> ruleAndUIValue= policyAdapter.getBrmsParamBody();
493                         String tempateValue= ruleAndUIValue.get("templateName");
494                         String valueFromDictionary= getValueFromDictionary(tempateValue);
495                         
496                         //Get the type of the UI Fields. 
497                         Map<String,String> typeOfUIField=findType(valueFromDictionary);
498                         String generatedRule=null;
499                         String body = "";
500                         
501                         try {
502                                 
503                                 try {
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();";
508                                         
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")
515                                                 {
516                                                         for(Map.Entry<String, String> fieldType:typeOfUIField.entrySet())
517                                                         {
518                                                                 if(fieldType.getKey().equalsIgnoreCase(entry.getKey()))
519                                                                 {
520                                                                         String key = entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1); 
521                                                                         if(fieldType.getValue()=="String")
522                                                                         {
523                                                                                 //Type is String
524                                                                                 generatedRule = generatedRule + "\n\t\tparams.set"
525                                                                                                 + key + "(\""
526                                                                                                 + entry.getValue() + "\");";
527                                                                         }
528                                                                         else{
529                                                                                 generatedRule = generatedRule + "\n\t\tparams.set"
530                                                                                                 + key  + "("
531                                                                                                 +  entry.getValue() + ");";
532                                                                         }
533                                                                 }
534                                                         }
535                                                 }
536                                         }
537                                         
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");
546                                 }
547                         }
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");
552                         }
553                         
554                         saveConfigurations(policyName,prevPolicyName,body);
555
556                         // Make sure the filename ends with an extension
557                         if (policyName.endsWith(".xml") == false) {
558                                 policyName = policyName + ".xml";
559                         }
560
561                         PolicyType configPolicy = (PolicyType) policyAdapter.getData();
562
563                         configPolicy.setDescription(policyAdapter.getPolicyDescription());
564
565                         configPolicy.setRuleCombiningAlgId(policyAdapter
566                                         .getRuleCombiningAlgId());
567
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,
575                                         fileName.length());
576                         if ((name == null) || (name.equals(""))) {
577                                 name = fileName.substring(fileName.lastIndexOf("/") + 1,
578                                                 fileName.length());
579                         }
580                         allOfOne.getMatch().add(createMatch("PolicyName", name));
581                         
582                         
583                         AllOfType allOf = new AllOfType();
584
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()));
599                         // Match for ttlDate
600                         allOf.getMatch().add(
601                                         createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
602                         AnyOfType anyOf = new AnyOfType();
603                         anyOf.getAllOf().add(allOfOne);
604                         anyOf.getAllOf().add(allOf);
605
606                         TargetType target = new TargetType();
607                         ((TargetType) target).getAnyOf().add(anyOf);
608
609                         // Adding the target to the policy element
610                         configPolicy.setTarget((TargetType) target);
611
612                         RuleType rule = new RuleType();
613                         rule.setRuleId(policyAdapter.getRuleID());
614
615                         rule.setEffect(EffectType.PERMIT);
616
617                         // Create Target in Rule
618                         AllOfType allOfInRule = new AllOfType();
619
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;
628                         try {
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");
635                         }
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);
642
643                         // Creating Config Match in rule Target
644                         MatchType configMatch = new MatchType();
645                         AttributeValueType configAttributeValue = new AttributeValueType();
646                         configAttributeValue.setDataType(STRING_DATATYPE);
647
648                         configAttributeValue.getContent().add("Config");
649
650                         configMatch.setAttributeValue(configAttributeValue);
651                         AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
652                         URI configURI = null;
653                         try {
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");
660                         }
661
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);
668
669                         allOfInRule.getMatch().add(accessMatch);
670                         allOfInRule.getMatch().add(configMatch);
671
672                         AnyOfType anyOfInRule = new AnyOfType();
673                         anyOfInRule.getAllOf().add(allOfInRule);
674
675                         TargetType targetInRule = new TargetType();
676                         targetInRule.getAnyOf().add(anyOfInRule);
677
678                         rule.setTarget(targetInRule);
679                         rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
680
681                         configPolicy
682                                         .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
683                                         .add(rule);
684                         policyAdapter.setPolicyData(configPolicy);
685
686                 } else {
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());
692                 }
693                 setPreparedToSave(true);
694                 return true;
695         }
696
697         // Data required for Advice part is setting here.
698         private AdviceExpressionsType getAdviceExpressions(int version,
699                         String fileName) {
700
701                 //Policy Config ID Assignment
702                 AdviceExpressionsType advices = new AdviceExpressionsType();
703                 AdviceExpressionType advice = new AdviceExpressionType();
704                 advice.setAdviceId("BRMSPARAMID");
705                 advice.setAppliesTo(EffectType.PERMIT);
706                 // For Configuration
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);
717
718                 // For Config file Url if configurations are provided.
719                 // URL ID Assignment
720                 final Path gitPath = Paths.get(policyAdapter.getUserGitPath()
721                                 .toString());
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);
737                 }
738                 String content = CONFIG_URL + "/Config/" + path + "."
739                                 + getConfigFile(policyName);
740
741                 AttributeValue.getContent().add(content);
742                 assignment2.setExpression(new ObjectFactory()
743                                 .createAttributeValue(AttributeValue));
744                 advice.getAttributeAssignmentExpression().add(assignment2);
745
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, "\\");
761                 } else {
762                         tokenizer = new StringTokenizer(policyDir, "/");
763                 }
764                 if (tokenizer != null) {
765                         while (tokenizer.hasMoreElements()) {
766                                 String value = tokenizer.nextToken();
767                                 buffer.append(value);
768                                 buffer.append(".");
769                         }
770                 }
771                 fileName = FilenameUtils.removeExtension(fileName);
772                 fileName = buffer.toString() + fileName + ".xml";
773                 System.out.println(fileName);
774                 String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
775                                 fileName.length());
776                 if ((name == null) || (name.equals(""))) {
777                         name = fileName.substring(fileName.lastIndexOf("/") + 1,
778                                         fileName.length());
779                 }
780                 System.out.println(name);
781                 attributeValue3.getContent().add(name);
782                 assignment3.setExpression(new ObjectFactory()
783                                 .createAttributeValue(attributeValue3));
784                 advice.getAttributeAssignmentExpression().add(assignment3);
785
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);
797
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);
809                 
810                 
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);
821                 
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("");
830
831                         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
832                         configNameAttributeValue7.setDataType(STRING_DATATYPE);
833                         configNameAttributeValue7.getContent().add(value);
834                         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
835
836                         advice.getAttributeAssignmentExpression().add(assignment7);
837                 }
838                 
839                 //Risk Attributes
840                 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
841                 assignment8.setAttributeId("RiskType");
842                 assignment8.setCategory(CATEGORY_RESOURCE);
843                 assignment8.setIssuer("");
844
845                 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
846                 configNameAttributeValue8.setDataType(STRING_DATATYPE);
847                 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
848                 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
849
850                 advice.getAttributeAssignmentExpression().add(assignment8);
851                 
852                 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
853                 assignment9.setAttributeId("RiskLevel");
854                 assignment9.setCategory(CATEGORY_RESOURCE);
855                 assignment9.setIssuer("");
856
857                 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
858                 configNameAttributeValue9.setDataType(STRING_DATATYPE);
859                 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
860                 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
861
862                 advice.getAttributeAssignmentExpression().add(assignment9);     
863
864                 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
865                 assignment10.setAttributeId("guard");
866                 assignment10.setCategory(CATEGORY_RESOURCE);
867                 assignment10.setIssuer("");
868
869                 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
870                 configNameAttributeValue10.setDataType(STRING_DATATYPE);
871                 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
872                 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
873
874                 advice.getAttributeAssignmentExpression().add(assignment10);
875
876                 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
877                 assignment11.setAttributeId("TTLDate");
878                 assignment11.setCategory(CATEGORY_RESOURCE);
879                 assignment11.setIssuer("");
880
881                 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
882                 configNameAttributeValue11.setDataType(STRING_DATATYPE);
883                 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
884                 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
885
886                 advice.getAttributeAssignmentExpression().add(assignment11);
887
888                 advices.getAdviceExpression().add(advice);
889                 return advices;
890         }
891
892         @Override
893         public Object getCorrectPolicyDataObject() {            
894                 return policyAdapter.getData();
895         }
896 }