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