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