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