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