0aaf1b1d2144d390e186c8ad91f67ea0aecc9944
[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.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.sql.Connection;
33 import java.sql.DriverManager;
34 import java.sql.ResultSet;
35 import java.sql.SQLException;
36 import java.sql.Statement;
37 import java.util.ArrayList;
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.regex.Matcher;
44 import java.util.regex.Pattern;
45
46 import org.apache.commons.io.FilenameUtils;
47 import org.openecomp.policy.common.logging.eelf.MessageCodes;
48 import org.openecomp.policy.common.logging.eelf.PolicyLogger;
49 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
50 import org.openecomp.policy.common.logging.flexlogger.Logger;
51 import org.openecomp.policy.pap.xacml.rest.controller.BRMSDictionaryController;
52 import org.openecomp.policy.rest.XACMLRestProperties;
53 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
54
55 import com.att.research.xacml.std.IdentifierImpl;
56 import com.att.research.xacml.util.XACMLProperties;
57
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; 
71
72 public class CreateBrmsParamPolicy extends Policy {
73         
74         private static final Logger LOGGER = FlexLogger.getLogger(CreateBrmsParamPolicy.class);
75
76         /*
77          * These are the parameters needed for DB access from the PAP
78          */
79         private static String papDbDriver = null;
80         private static String papDbUrl = null;
81         private static String papDbUser = null;
82         private static String papDbPassword = null;
83
84         public CreateBrmsParamPolicy() {
85                 super();
86         }
87
88         public CreateBrmsParamPolicy(PolicyRestAdapter policyAdapter) {
89                 this.policyAdapter = policyAdapter;
90                 this.policyAdapter.setConfigType(policyAdapter.getConfigType());
91
92         }
93         
94         public String expandConfigBody(String ruleContents, Map<String, String> brmsParamBody) { 
95                          
96                         Set<String> keySet= new HashSet<String>();
97                         
98                         Map<String,String> copyMap=new HashMap<>();
99                         copyMap.putAll(brmsParamBody);
100                         copyMap.put("policyName", policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")));
101                         copyMap.put("policyScope", policyAdapter.getDomainDir());
102                         copyMap.put("policyVersion",policyAdapter.getHighestVersion().toString());
103                         
104                         //Finding all the keys in the Map data-structure.
105                         keySet= copyMap.keySet();
106                         Iterator<String> iterator = keySet.iterator(); 
107                         Pattern p;
108                         Matcher m;
109                         while(iterator.hasNext()) {
110                                 //Converting the first character of the key into a lower case. 
111                                 String input= iterator.next();
112                                 String output  = Character.toLowerCase(input.charAt(0)) +
113                                    (input.length() > 1 ? input.substring(1) : "");
114                                 //Searching for a pattern in the String using the key. 
115                                 p=Pattern.compile("\\$\\{"+output+"\\}");       
116                                 m=p.matcher(ruleContents);
117                                 //Replacing the value with the inputs provided by the user in the editor. 
118                                 String finalInput = copyMap.get(input);
119                                 if(finalInput.contains("$")){
120                                         finalInput = finalInput.replace("$", "\\$");
121                                 }
122                                 ruleContents=m.replaceAll(finalInput);
123                         }
124                         return ruleContents; 
125         } 
126                          
127
128     
129         // Utility to read json data from the existing file to a string
130         static String readFile(String path, Charset encoding) throws IOException {
131
132                 byte[] encoded = Files.readAllBytes(Paths.get(path));
133                 return new String(encoded, encoding);
134
135         }
136         
137         // Saving the Configurations file at server location for config policy.
138         protected void saveConfigurations(String policyName, String ruleBody) {
139                 try {
140                         if (policyName.endsWith(".xml")) {
141                                 policyName = policyName.substring(0,
142                                                 policyName.lastIndexOf(".xml"));
143                         }
144                         PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt");
145                         String expandedBody=expandConfigBody(ruleBody,policyAdapter.getBrmsParamBody());
146                         out.println(expandedBody);
147                         policyAdapter.setJsonBody(expandedBody);
148                         policyAdapter.setConfigBodyData(expandedBody);
149                         out.close();
150                         
151
152                 } catch (Exception e) {
153                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving configuration file");
154                 }
155         }
156
157
158         // Here we are adding the extension for the configurations file based on the
159         // config type selection for saving.
160         private String getConfigFile(String filename) {
161                 filename = FilenameUtils.removeExtension(filename);
162                 if (filename.endsWith(".txt")) {
163                         filename = filename.substring(0, filename.length() - 3);
164                 }
165
166                 filename = filename + ".txt";
167                 return filename;
168         }
169
170         // Validations for Config form
171         public boolean validateConfigForm() {
172
173                 // Validating mandatory Fields.
174                 isValidForm = true;
175                 return isValidForm;
176
177         }
178
179         @Override
180         public Map<String, String> savePolicies() throws Exception {
181                 
182                 Map<String, String> successMap = new HashMap<String,String>();
183                 if(isPolicyExists()){
184                         successMap.put("EXISTS", "This Policy already exist on the PAP");
185                         return successMap;
186                 }
187                 
188                 if (!isPreparedToSave()) {
189                         prepareToSave();
190                 }
191                 // Until here we prepared the data and here calling the method to create
192                 // xml.
193                 Path newPolicyPath = null;
194                 newPolicyPath = Paths.get(policyAdapter.getNewFileName());
195                 
196                 Boolean dbIsUpdated = true;
197
198                 successMap = new HashMap<String, String>();
199                 if (dbIsUpdated) {
200                         successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject());
201                 } else {
202                         PolicyLogger.error("Failed to Update the Database Dictionary Tables.");
203                         successMap.put("error", "DB UPDATE");
204                 }
205                 return successMap;
206         }
207         
208         private String getValueFromDictionary(String templateName){
209                 
210                 Connection con = null;
211                 Statement st = null;
212                 ResultSet rs = null;
213                 
214                 /*
215                  * Retrieve the property values for db access from the xacml.pap.properties
216                  */
217                 papDbDriver = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_DRIVER);
218                 papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL);
219                 papDbUser = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_USER);
220                 papDbPassword = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_PASSWORD);
221                 
222                 String ruleTemplate=null;
223                 
224                 try {
225                         //Get DB Connection
226                         Class.forName(papDbDriver);
227                         con = DriverManager.getConnection(papDbUrl,papDbUser,papDbPassword);
228                         st = con.createStatement();
229                         
230                         String queryString="select rule from BRMSParamTemplate where param_template_name=\"";
231                         queryString=queryString+templateName+"\"";
232                         
233                         rs = st.executeQuery(queryString);
234                         if(rs.next()){
235                                 ruleTemplate=rs.getString("rule");
236                         }
237                         rs.close();
238                 }catch (ClassNotFoundException e) {
239                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate");
240                 } catch (SQLException e) {
241                         PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate");
242                 } finally {
243                         try{
244                                 if (con!=null) con.close();
245                                 if (rs!=null) rs.close();
246                                 if (st!=null) st.close();
247                         } catch (Exception ex){
248                                 PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, ex, "CreateBrmsParamPolicy", "Exception querying BRMSParamTemplate");
249                         }
250                 }
251                 return ruleTemplate;
252                 
253         }
254         
255         protected Map<String, String> findType(String rule) {
256                 Map<String, String> mapFieldType= new HashMap<String,String>();
257                 if(rule!=null){
258                         try {
259                                 String params = "";
260                                 Boolean flag = false;
261                                 Boolean comment = false;
262                                 String lines[] = rule.split("\n");
263                                 for(String line : lines){
264                                         if (line.isEmpty() || line.startsWith("//")) {
265                                                 continue;
266                                         }
267                                         if (line.startsWith("/*")) {
268                                                 comment = true;
269                                                 continue;
270                                         }
271                                         if (line.contains("//")) {
272                                                 if(!(line.contains("http://") || line.contains("https://"))){
273                                                         line = line.split("\\/\\/")[0];
274                                                 }
275                                         }
276                                         if (line.contains("/*")) {
277                                                 comment = true;
278                                                 if (line.contains("*/")) {
279                                                         try {
280                                                                 comment = false;
281                                                                 line = line.split("\\/\\*")[0]
282                                                                                 + line.split("\\*\\/")[1].replace("*/", "");
283                                                         } catch (Exception e) {
284                                                                 line = line.split("\\/\\*")[0];
285                                                         }
286                                                 } else {
287                                                         line = line.split("\\/\\*")[0];
288                                                 }
289                                         }
290                                         if (line.contains("*/")) {
291                                                 comment = false;
292                                                 try {
293                                                         line = line.split("\\*\\/")[1].replace("*/", "");
294                                                 } catch (Exception e) {
295                                                         line = "";
296                                                 }
297                                         }
298                                         if (comment) {
299                                                 continue;
300                                         }
301                                         if (flag) {
302                                                 params = params + line;
303                                         }
304                                         if (line.contains("declare Params")) {
305                                                 params = params + line;
306                                                 flag = true;
307                                         }
308                                         if (line.contains("end") && flag) {
309                                                 break;
310                                         }
311                                 }
312                                 params = params.replace("declare Params", "").replace("end", "")
313                                                 .replaceAll("\\s+", "");
314                                 String[] components = params.split(":");
315                                 String caption = "";
316                                 for (int i = 0; i < components.length; i++) {
317                                         String type = "";
318                                         if (i == 0) {
319                                                 caption = components[i];
320                                         }
321                                         if(caption.equals("")){
322                                                 break;
323                                         }
324                                         String nextComponent = "";
325                                         try {
326                                                 nextComponent = components[i + 1];
327                                         } catch (Exception e) {
328                                                 nextComponent = components[i];
329                                         }
330                                         //If the type is of type String then we add the UI Item and type to the map. 
331                                         if (nextComponent.startsWith("String")) {
332                                                 type = "String";
333                                                 mapFieldType.put(caption, type);
334                                                 caption = nextComponent.replace("String", "");
335                                         } else if (nextComponent.startsWith("int")) {
336                                                 type = "int";
337                                                 mapFieldType.put(caption, type);
338                                                 caption = nextComponent.replace("int", "");
339                                         }
340                                 }
341                         } catch (Exception e) {
342                                 PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CreateBrmsParamPolicy", "Exception parsing file in findType");
343                         }
344                 }
345                 return mapFieldType;
346         }
347         
348         // This is the method for preparing the policy for saving. We have broken it
349         // out
350         // separately because the fully configured policy is used for multiple
351         // things
352         @Override
353         public boolean prepareToSave() throws Exception {
354                 
355                 if (isPreparedToSave()) {
356                         // we have already done this
357                         return true;
358                 }
359
360                 int version = 0;
361                 String policyID = policyAdapter.getPolicyID();
362                 version = policyAdapter.getHighestVersion();
363
364                 // Create the Instance for pojo, PolicyType object is used in
365                 // marshalling.
366                 if (policyAdapter.getPolicyType().equals("Config")) {
367                         PolicyType policyConfig = new PolicyType();
368
369                         policyConfig.setVersion(Integer.toString(version));
370                         policyConfig.setPolicyId(policyID);
371                         policyConfig.setTarget(new TargetType());
372                         policyAdapter.setData(policyConfig);
373                 }
374
375                 policyName = policyAdapter.getNewFileName();
376                 
377                 if (policyAdapter.getData() != null) {  
378                         Map<String,String> ruleAndUIValue= policyAdapter.getBrmsParamBody();
379                         String tempateValue= ruleAndUIValue.get("templateName");
380                         String valueFromDictionary= getValueFromDictionary(tempateValue);
381                         
382                         //Get the type of the UI Fields. 
383                         Map<String,String> typeOfUIField=findType(valueFromDictionary);
384                         String generatedRule=null;
385                         String body = "";
386                         
387                         try {
388                                 
389                                 try {
390                                         body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
391                                                                 "<$%BRMSParamTemplate=" + tempateValue + "%$> \n */ \n";
392                                         body = body +  valueFromDictionary + "\n";
393                                         generatedRule = "rule \"" +policyName.substring(0, policyName.replace(".xml", "").lastIndexOf(".")) +".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();";
394                                         
395                                         //We first read the map data structure(ruleAndUIValue) received from the PAP-ADMIN
396                                         //We ignore if the key is "templateName as we are interested only in the UI fields and its value. 
397                                         //We have one more map data structure(typeOfUIField) created by parsing the Drools rule. 
398                                         //From the type of the UI field(String/int) we structure whether to put the "" or not. 
399                                         for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) {
400                                                 if(entry.getKey()!="templateName")
401                                                 {
402                                                         for(Map.Entry<String, String> fieldType:typeOfUIField.entrySet())
403                                                         {
404                                                                 if(fieldType.getKey().equalsIgnoreCase(entry.getKey()))
405                                                                 {
406                                                                         String key = entry.getKey().substring(0, 1).toUpperCase() + entry.getKey().substring(1); 
407                                                                         if(fieldType.getValue()=="String")
408                                                                         {
409                                                                                 //Type is String
410                                                                                 generatedRule = generatedRule + "\n\t\tparams.set"
411                                                                                                 + key + "(\""
412                                                                                                 + entry.getValue() + "\");";
413                                                                         }
414                                                                         else{
415                                                                                 generatedRule = generatedRule + "\n\t\tparams.set"
416                                                                                                 + key  + "("
417                                                                                                 +  entry.getValue() + ");";
418                                                                         }
419                                                                 }
420                                                         }
421                                                 }
422                                         }
423                                         
424                                         generatedRule = generatedRule
425                                                         + "\n\t\tinsert(params);\nend";
426                                         LOGGER.info("New rule generated with :" + generatedRule);
427                                         body = body + generatedRule;
428                                 } catch (Exception e) {
429                                         PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
430                                 }
431                         }
432                         catch (Exception e) {
433                                 PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy");
434                         }
435                         
436                         saveConfigurations(policyName,body);
437                         
438                         // Make sure the filename ends with an extension
439                         if (policyName.endsWith(".xml") == false) {
440                                 policyName = policyName + ".xml";
441                         }
442
443                         PolicyType configPolicy = (PolicyType) policyAdapter.getData();
444
445                         configPolicy.setDescription(policyAdapter.getPolicyDescription());
446
447                         configPolicy.setRuleCombiningAlgId(policyAdapter.getRuleCombiningAlgId());
448
449                         AllOfType allOfOne = new AllOfType();
450
451                         String fileName = policyAdapter.getNewFileName();
452                         String name = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
453                         if ((name == null) || (name.equals(""))) {
454                                 name = fileName.substring(fileName.lastIndexOf("/") + 1,
455                                                 fileName.length());
456                         }
457                         allOfOne.getMatch().add(createMatch("PolicyName", name));
458                         
459                         
460                         AllOfType allOf = new AllOfType();
461
462                         // Match for ECOMPName
463                         allOf.getMatch().add(createMatch("ECOMPName", policyAdapter.getEcompName()));
464                         allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName()));
465                         // Match for riskType
466                         allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType()));
467                         // Match for riskLevel
468                         allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel())));
469                         // Match for riskguard
470                         allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard()));
471                         // Match for ttlDate
472                         allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate()));
473                         AnyOfType anyOf = new AnyOfType();
474                         anyOf.getAllOf().add(allOfOne);
475                         anyOf.getAllOf().add(allOf);
476
477                         TargetType target = new TargetType();
478                         ((TargetType) target).getAnyOf().add(anyOf);
479
480                         // Adding the target to the policy element
481                         configPolicy.setTarget((TargetType) target);
482
483                         RuleType rule = new RuleType();
484                         rule.setRuleId(policyAdapter.getRuleID());
485
486                         rule.setEffect(EffectType.PERMIT);
487
488                         // Create Target in Rule
489                         AllOfType allOfInRule = new AllOfType();
490
491                         // Creating match for ACCESS in rule target
492                         MatchType accessMatch = new MatchType();
493                         AttributeValueType accessAttributeValue = new AttributeValueType();
494                         accessAttributeValue.setDataType(STRING_DATATYPE);
495                         accessAttributeValue.getContent().add("ACCESS");
496                         accessMatch.setAttributeValue(accessAttributeValue);
497                         AttributeDesignatorType accessAttributeDesignator = new AttributeDesignatorType();
498                         URI accessURI = null;
499                         try {
500                                 accessURI = new URI(ACTION_ID);
501                         } catch (URISyntaxException e) {
502                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", "Exception creating ACCESS URI");
503                         }
504                         accessAttributeDesignator.setCategory(CATEGORY_ACTION);
505                         accessAttributeDesignator.setDataType(STRING_DATATYPE);
506                         accessAttributeDesignator.setAttributeId(new IdentifierImpl(
507                                         accessURI).stringValue());
508                         accessMatch.setAttributeDesignator(accessAttributeDesignator);
509                         accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
510
511                         // Creating Config Match in rule Target
512                         MatchType configMatch = new MatchType();
513                         AttributeValueType configAttributeValue = new AttributeValueType();
514                         configAttributeValue.setDataType(STRING_DATATYPE);
515
516                         configAttributeValue.getContent().add("Config");
517
518                         configMatch.setAttributeValue(configAttributeValue);
519                         AttributeDesignatorType configAttributeDesignator = new AttributeDesignatorType();
520                         URI configURI = null;
521                         try {
522                                 configURI = new URI(RESOURCE_ID);
523                         } catch (URISyntaxException e) {
524                                 PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateBrmsParamPolicy", "Exception creating Config URI");
525                         }
526
527                         configAttributeDesignator.setCategory(CATEGORY_RESOURCE);
528                         configAttributeDesignator.setDataType(STRING_DATATYPE);
529                         configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue());
530                         configMatch.setAttributeDesignator(configAttributeDesignator);
531                         configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE);
532
533                         allOfInRule.getMatch().add(accessMatch);
534                         allOfInRule.getMatch().add(configMatch);
535
536                         AnyOfType anyOfInRule = new AnyOfType();
537                         anyOfInRule.getAllOf().add(allOfInRule);
538
539                         TargetType targetInRule = new TargetType();
540                         targetInRule.getAnyOf().add(anyOfInRule);
541
542                         rule.setTarget(targetInRule);
543                         rule.setAdviceExpressions(getAdviceExpressions(version, policyName));
544
545                         configPolicy
546                                         .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition()
547                                         .add(rule);
548                         policyAdapter.setPolicyData(configPolicy);
549
550                 } else {
551                         PolicyLogger.error("Unsupported data object."
552                                         + policyAdapter.getData().getClass().getCanonicalName());
553                 }
554                 setPreparedToSave(true);
555                 return true;
556         }
557
558         // Data required for Advice part is setting here.
559         private AdviceExpressionsType getAdviceExpressions(int version,
560                         String fileName) {
561
562                 //Policy Config ID Assignment
563                 AdviceExpressionsType advices = new AdviceExpressionsType();
564                 AdviceExpressionType advice = new AdviceExpressionType();
565                 advice.setAdviceId("BRMSPARAMID");
566                 advice.setAppliesTo(EffectType.PERMIT);
567                 // For Configuration
568                 AttributeAssignmentExpressionType assignment1 = new AttributeAssignmentExpressionType();
569                 assignment1.setAttributeId("type");
570                 assignment1.setCategory(CATEGORY_RESOURCE);
571                 assignment1.setIssuer("");
572                 AttributeValueType configNameAttributeValue = new AttributeValueType();
573                 configNameAttributeValue.setDataType(STRING_DATATYPE);
574                 configNameAttributeValue.getContent().add("Configuration");
575                 assignment1.setExpression(new ObjectFactory()
576                                 .createAttributeValue(configNameAttributeValue));
577                 advice.getAttributeAssignmentExpression().add(assignment1);
578
579                 // For Config file Url if configurations are provided.
580                 // URL ID Assignment
581                 AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType();
582                 assignment2.setAttributeId("URLID");
583                 assignment2.setCategory(CATEGORY_RESOURCE);
584                 assignment2.setIssuer("");
585                 AttributeValueType AttributeValue = new AttributeValueType();
586                 AttributeValue.setDataType(URI_DATATYPE);
587
588                 String content = CONFIG_URL + "/Config/"+ getConfigFile(policyName);
589
590                 AttributeValue.getContent().add(content);
591                 assignment2.setExpression(new ObjectFactory()
592                                 .createAttributeValue(AttributeValue));
593                 advice.getAttributeAssignmentExpression().add(assignment2);
594
595                 // Policy Name Assignment
596                 AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType();
597                 assignment3.setAttributeId("PolicyName");
598                 assignment3.setCategory(CATEGORY_RESOURCE);
599                 assignment3.setIssuer("");
600                 AttributeValueType attributeValue3 = new AttributeValueType();
601                 attributeValue3.setDataType(STRING_DATATYPE);
602                 fileName = FilenameUtils.removeExtension(fileName);
603                 fileName = fileName + ".xml";
604                 String name = fileName.substring(fileName.lastIndexOf("\\") + 1,
605                                 fileName.length());
606                 if ((name == null) || (name.equals(""))) {
607                         name = fileName.substring(fileName.lastIndexOf("/") + 1,
608                                         fileName.length());
609                 }
610                 attributeValue3.getContent().add(name);
611                 assignment3.setExpression(new ObjectFactory()
612                                 .createAttributeValue(attributeValue3));
613                 advice.getAttributeAssignmentExpression().add(assignment3);
614
615                 // Version Number Assignment
616                 AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType();
617                 assignment4.setAttributeId("VersionNumber");
618                 assignment4.setCategory(CATEGORY_RESOURCE);
619                 assignment4.setIssuer("");
620                 AttributeValueType configNameAttributeValue4 = new AttributeValueType();
621                 configNameAttributeValue4.setDataType(STRING_DATATYPE);
622                 configNameAttributeValue4.getContent().add(Integer.toString(version));
623                 assignment4.setExpression(new ObjectFactory()
624                                 .createAttributeValue(configNameAttributeValue4));
625                 advice.getAttributeAssignmentExpression().add(assignment4);
626
627                 // Ecomp Name Assignment
628                 AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
629                 assignment5.setAttributeId("matching:" + ECOMPID);
630                 assignment5.setCategory(CATEGORY_RESOURCE);
631                 assignment5.setIssuer("");
632                 AttributeValueType configNameAttributeValue5 = new AttributeValueType();
633                 configNameAttributeValue5.setDataType(STRING_DATATYPE);
634                 configNameAttributeValue5.getContent().add(policyAdapter.getEcompName());
635                 assignment5.setExpression(new ObjectFactory()
636                                 .createAttributeValue(configNameAttributeValue5));
637                 advice.getAttributeAssignmentExpression().add(assignment5);
638                 
639                 
640                 //Config Name Assignment
641                 AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
642                 assignment6.setAttributeId("matching:" +CONFIGID);
643                 assignment6.setCategory(CATEGORY_RESOURCE);
644                 assignment6.setIssuer("");
645                 AttributeValueType configNameAttributeValue6 = new AttributeValueType();
646                 configNameAttributeValue6.setDataType(STRING_DATATYPE);
647                 configNameAttributeValue6.getContent().add(policyAdapter.getConfigName());
648                 assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6));
649                 advice.getAttributeAssignmentExpression().add(assignment6);
650         // Adding Controller Information. 
651         if(policyAdapter.getBrmsController()!=null){
652             BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
653             advice.getAttributeAssignmentExpression().add(
654                         createResponseAttributes("controller:"+ policyAdapter.getBrmsController(), 
655                                 brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController()));
656         }
657         
658         // Adding Dependencies. 
659         if(policyAdapter.getBrmsDependency()!=null){
660             BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController();
661             ArrayList<String> dependencies = new ArrayList<String>();
662             StringBuilder key = new StringBuilder();
663             for(String dependencyName: policyAdapter.getBrmsDependency()){
664                 dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency());
665                 key.append(dependencyName + ",");
666             }
667             advice.getAttributeAssignmentExpression().add(
668                         createResponseAttributes("dependencies:"+key.toString(), dependencies.toString()));
669         }
670         
671         // Dynamic Field Config Attributes. 
672                 Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes();
673                 for (String keyField : dynamicFieldConfigAttributes.keySet()) {
674                         advice.getAttributeAssignmentExpression().add(createResponseAttributes("key:"+keyField, dynamicFieldConfigAttributes.get(keyField)));
675                 }
676                 
677                 //Risk Attributes
678                 AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
679                 assignment8.setAttributeId("RiskType");
680                 assignment8.setCategory(CATEGORY_RESOURCE);
681                 assignment8.setIssuer("");
682
683                 AttributeValueType configNameAttributeValue8 = new AttributeValueType();
684                 configNameAttributeValue8.setDataType(STRING_DATATYPE);
685                 configNameAttributeValue8.getContent().add(policyAdapter.getRiskType());
686                 assignment8.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue8));
687
688                 advice.getAttributeAssignmentExpression().add(assignment8);
689                 
690                 AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType();
691                 assignment9.setAttributeId("RiskLevel");
692                 assignment9.setCategory(CATEGORY_RESOURCE);
693                 assignment9.setIssuer("");
694
695                 AttributeValueType configNameAttributeValue9 = new AttributeValueType();
696                 configNameAttributeValue9.setDataType(STRING_DATATYPE);
697                 configNameAttributeValue9.getContent().add(policyAdapter.getRiskLevel());
698                 assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9));
699
700                 advice.getAttributeAssignmentExpression().add(assignment9);     
701
702                 AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType();
703                 assignment10.setAttributeId("guard");
704                 assignment10.setCategory(CATEGORY_RESOURCE);
705                 assignment10.setIssuer("");
706
707                 AttributeValueType configNameAttributeValue10 = new AttributeValueType();
708                 configNameAttributeValue10.setDataType(STRING_DATATYPE);
709                 configNameAttributeValue10.getContent().add(policyAdapter.getGuard());
710                 assignment10.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue10));
711
712                 advice.getAttributeAssignmentExpression().add(assignment10);
713
714                 AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
715                 assignment11.setAttributeId("TTLDate");
716                 assignment11.setCategory(CATEGORY_RESOURCE);
717                 assignment11.setIssuer("");
718
719                 AttributeValueType configNameAttributeValue11 = new AttributeValueType();
720                 configNameAttributeValue11.setDataType(STRING_DATATYPE);
721                 configNameAttributeValue11.getContent().add(policyAdapter.getTtlDate());
722                 assignment11.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue11));
723
724                 advice.getAttributeAssignmentExpression().add(assignment11);
725
726                 advices.getAdviceExpression().add(advice);
727                 return advices;
728         }
729
730         @Override
731         public Object getCorrectPolicyDataObject() {            
732                 return policyAdapter.getData();
733         }
734         
735     private AttributeAssignmentExpressionType  createResponseAttributes(String key, String value){
736         AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
737         assignment7.setAttributeId(key);
738         assignment7.setCategory(CATEGORY_RESOURCE);
739         assignment7.setIssuer("");
740         AttributeValueType configNameAttributeValue7 = new AttributeValueType();
741         configNameAttributeValue7.setDataType(STRING_DATATYPE);
742         configNameAttributeValue7.getContent().add(value);
743         assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7));
744         return assignment7;
745     }
746 }