2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.policy.controller;
24 import java.io.BufferedReader;
26 import java.io.FileNotFoundException;
27 import java.io.FileReader;
28 import java.io.IOException;
29 import java.io.PrintWriter;
30 import java.nio.file.Files;
31 import java.nio.file.Path;
32 import java.nio.file.Paths;
33 import java.text.DateFormat;
34 import java.text.ParseException;
35 import java.text.SimpleDateFormat;
36 import java.util.ArrayList;
37 import java.util.Date;
38 import java.util.HashMap;
39 import java.util.Iterator;
40 import java.util.LinkedHashMap;
41 import java.util.List;
43 import java.util.UUID;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47 import javax.xml.bind.JAXBElement;
49 import org.json.JSONObject;
50 import org.openecomp.policy.adapter.PolicyAdapter;
51 import org.openecomp.policy.admin.PolicyNotificationMail;
52 import org.openecomp.policy.admin.RESTfulPAPEngine;
53 import org.openecomp.policy.dao.PolicyVersionDao;
54 import org.openecomp.policy.dao.RuleAlgorithmsDao;
55 import org.openecomp.policy.dao.WatchPolicyNotificationDao;
56 import org.openecomp.policy.elk.client.PolicyElasticSearchController;
57 import org.openecomp.policy.rest.dao.BRMSParamTemplateDao;
58 import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
59 import org.openecomp.policy.rest.jpa.PolicyVersion;
60 import org.openecomp.policy.rest.jpa.RuleAlgorithms;
61 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
62 import org.openecomp.portalsdk.core.web.support.UserUtils;
63 import org.springframework.beans.factory.annotation.Autowired;
64 import org.springframework.stereotype.Controller;
65 import org.springframework.web.bind.annotation.RequestMapping;
66 import org.springframework.web.servlet.ModelAndView;
68 import com.att.research.xacml.api.XACML3;
69 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
70 import org.openecomp.policy.xacml.util.XACMLPolicyScanner;
71 import com.fasterxml.jackson.databind.DeserializationFeature;
72 import com.fasterxml.jackson.databind.JsonNode;
73 import com.fasterxml.jackson.databind.ObjectMapper;
74 import com.google.common.base.Joiner;
76 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
77 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
78 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
79 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
80 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
81 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
82 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
83 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
84 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
85 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
87 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
88 import org.openecomp.policy.common.logging.flexlogger.Logger;
92 public class CreateBRMSParamController extends RestrictedBaseController {
93 private static final Logger logger = FlexLogger.getLogger(CreateBRMSParamController.class);
95 private static RuleAlgorithmsDao ruleAlgorithmsDao;
96 private static BRMSParamTemplateDao bRMSParamTemplateDao;
97 private static PolicyVersionDao policyVersionDao;
98 private static WatchPolicyNotificationDao policyNotificationDao;
101 private CreateBRMSParamController(RuleAlgorithmsDao ruleAlgorithmsDao, BRMSParamTemplateDao bRMSParamTemplateDao, PolicyVersionDao policyVersionDao,
102 WatchPolicyNotificationDao policyNotificationDao){
103 CreateBRMSParamController.policyVersionDao = policyVersionDao;
104 CreateBRMSParamController.ruleAlgorithmsDao = ruleAlgorithmsDao;
105 CreateBRMSParamController.bRMSParamTemplateDao = bRMSParamTemplateDao;
106 CreateBRMSParamController.policyNotificationDao = policyNotificationDao;
109 public CreateBRMSParamController(){}
110 protected PolicyAdapter policyAdapter = null;
111 private ArrayList<Object> attributeList;
112 private String ruleID = "";
114 private HashMap<String, String> dynamicLayoutMap;
116 public String newPolicyID() {
117 return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"),
118 PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID());
121 @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
122 public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{
123 dynamicLayoutMap = new HashMap<String, String>();
124 ObjectMapper mapper = new ObjectMapper();
125 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
126 JsonNode root = mapper.readTree(request.getReader());
127 String rule = findRule(root.get("policyData").toString().replaceAll("^\"|\"$", ""));
129 response.setCharacterEncoding("UTF-8");
130 response.setContentType("application / json");
131 request.setCharacterEncoding("UTF-8");
133 PrintWriter out = response.getWriter();
134 String responseString = mapper.writeValueAsString(dynamicLayoutMap);
135 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
136 out.write(j.toString());
140 protected String findRule(String ruleTemplate) {
141 for (BRMSParamTemplate bRMSParamTemplate: bRMSParamTemplateDao.getBRMSParamTemplateData()){
142 if(bRMSParamTemplate.getRuleName().equals(ruleTemplate)){
143 return bRMSParamTemplate.getRule();
149 protected void generateUI(String rule) {
153 Boolean flag = false;
154 Boolean comment = false;
155 String lines[] = rule.split("\n");
156 for(String line : lines){
157 if (line.isEmpty() || line.startsWith("//")) {
160 if (line.startsWith("/*")) {
164 if (line.contains("//")) {
165 line = line.split("\\/\\/")[0];
167 if (line.contains("/*")) {
169 if (line.contains("*/")) {
172 line = line.split("\\/\\*")[0]
173 + line.split("\\*\\/")[1].replace("*/", "");
174 } catch (Exception e) {
175 line = line.split("\\/\\*")[0];
178 line = line.split("\\/\\*")[0];
181 if (line.contains("*/")) {
184 line = line.split("\\*\\/")[1].replace("*/", "");
185 } catch (Exception e) {
193 params = params + line;
195 if (line.contains("declare Params")) {
196 params = params + line;
199 if (line.contains("end") && flag) {
203 params = params.replace("declare Params", "").replace("end", "")
204 .replaceAll("\\s+", "");
205 String[] components = params.split(":");
207 for (int i = 0; i < components.length; i++) {
210 caption = components[i];
212 if(caption.equals("")){
215 String nextComponent = "";
217 nextComponent = components[i + 1];
218 } catch (Exception e) {
219 nextComponent = components[i];
221 if (nextComponent.startsWith("String")) {
223 createField(caption, type);
224 caption = nextComponent.replace("String", "");
225 } else if (nextComponent.startsWith("int")) {
227 createField(caption, type);
228 caption = nextComponent.replace("int", "");
231 } catch (Exception e) {
232 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
237 private String convertDate(String dateTTL) {
238 String formateDate = null;
239 String[] date = dateTTL.split("T");
240 String[] parts = date[0].split("-");
242 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
246 private void createField(String caption, String type) {
247 dynamicLayoutMap.put(caption, type);
250 @RequestMapping(value={"/policyController/save_BRMSParamPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
251 public ModelAndView saveBRMSParamPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{
253 String userId = UserUtils.getUserIdFromCookie(request);
254 RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine();
255 ObjectMapper mapper = new ObjectMapper();
256 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
257 JsonNode root = mapper.readTree(request.getReader());
258 PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class);
260 if (policyData.getTtlDate()==null){
261 policyData.setTtlDate("NA");
263 String dateTTL = policyData.getTtlDate();
264 String newDate = convertDate(dateTTL);
265 policyData.setTtlDate(newDate);
268 if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
269 policyData.isEditPolicy = true;
271 if(root.get("policyData").get("model").get("path").size() != 0){
273 for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){
274 dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator;
276 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
278 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
281 int highestVersion = 0;
282 int descriptionVersion = 0;
283 //get the highest version of policy from policy version table.
284 //getting the sub scope domain where the policy is created or updated
285 String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_BRMS_Param_" + policyData.getPolicyName();
286 List<PolicyVersion> policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName);
287 if (policyVersionList.size() > 0) {
288 for(int i = 0; i < policyVersionList.size(); i++) {
289 PolicyVersion entityItem = policyVersionList.get(i);
290 if(entityItem.getPolicyName().equals(dbCheckPolicyName)){
291 highestVersion = entityItem.getHigherVersion();
295 if(highestVersion != 0){
296 version = highestVersion;
297 descriptionVersion = highestVersion +1;
300 descriptionVersion = 1;
303 //set policy adapter values for Building JSON object containing policy data
304 String createdBy = "";
305 String modifiedBy = userId;
306 if(descriptionVersion == 1){
309 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
310 File policyPath = new File(policyName);
312 createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
313 } catch (IOException e) {
318 policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:");
319 Map<String, String> successMap = new HashMap<String, String>();
320 Map<String, String> attributeMap = new HashMap<String, String>();
321 //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON
322 List<RuleAlgorithms> ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms();
323 for (int i = 0; i < ruleAlgorithmsList.size(); i++) {
324 RuleAlgorithms a = ruleAlgorithmsList.get(i);
325 if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) {
326 policyData.setRuleCombiningAlgId(a.getXacmlId());
330 if(policyData.getAttributes().size() > 0){
331 for(Object attribute : policyData.getAttributes()){
332 if(attribute instanceof LinkedHashMap<?, ?>){
333 String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString();
334 String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString();
335 attributeMap.put(key, value);
340 policyData.setEcompName("DROOLS");
341 policyData.setConfigName("BRMS_PARAM_RULE");
342 policyData.setDynamicFieldConfigAttributes(attributeMap);
343 //convert drl rule and UI parameters into a map
344 Map<String, String> drlRuleAndUIParams = new HashMap<String, String>();
345 // If there is any dynamic field create the matches here
346 String key="templateName";
347 String value=(String) policyData.getRuleName();
348 drlRuleAndUIParams.put(key, value);
349 System.out.println(policyData.getRuleData());
350 if(policyData.getRuleData().size() > 0){
351 for(Object keyValue: policyData.getRuleData().keySet()){
352 drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString());
355 policyData.setBRMSParamBody(drlRuleAndUIParams);
356 if (policyData.isEditPolicy()){
357 //increment the version and set in policyAdapter
358 policyData.setVersion(String.valueOf(version));
359 policyData.setHighestVersion(version);
360 policyData.setPolicyID(this.newPolicyID());
361 policyData.setRuleID(ruleID);
362 successMap = engine.updatePolicyRequest(policyData);
364 //send it for policy creation
365 policyData.setVersion(String.valueOf(version));
366 policyData.setHighestVersion(version);
367 successMap = engine.createPolicyRequest(policyData);
371 if (successMap.containsKey("success")) {
372 // Add it into our tree
373 Path finalPolicyPath = null;
374 finalPolicyPath = Paths.get(successMap.get("success"));
375 PolicyElasticSearchController controller = new PolicyElasticSearchController();
376 controller.updateElk(finalPolicyPath.toString());
377 File file = finalPolicyPath.toFile();
379 String policyName = file.toString();
380 String removePath = policyName.substring(policyName.indexOf("repository")+11);
381 String removeXml = removePath.replace(".xml", "");
382 String removeExtension = removeXml.substring(0, removeXml.indexOf("."));
383 List<PolicyVersion> versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension);
384 if (versionList.size() > 0) {
385 for(int i = 0; i < versionList.size(); i++) {
386 PolicyVersion entityItem = versionList.get(i);
387 if(entityItem.getPolicyName().equals(removeExtension)){
388 version = entityItem.getHigherVersion() +1;
389 entityItem.setActiveVersion(version);
390 entityItem.setHigherVersion(version);
391 entityItem.setModifiedBy(userId);
392 policyVersionDao.update(entityItem);
393 if(policyData.isEditPolicy){
394 PolicyNotificationMail email = new PolicyNotificationMail();
395 String mode = "EditPolicy";
396 String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
397 email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao);
402 PolicyVersion entityItem = new PolicyVersion();
403 entityItem.setActiveVersion(version);
404 entityItem.setHigherVersion(version);
405 entityItem.setPolicyName(removeExtension);
406 entityItem.setCreatedBy(userId);
407 entityItem.setModifiedBy(userId);
408 policyVersionDao.Save(entityItem);
413 response.setCharacterEncoding("UTF-8");
414 response.setContentType("application / json");
415 request.setCharacterEncoding("UTF-8");
417 PrintWriter out = response.getWriter();
418 String responseString = mapper.writeValueAsString(successMap);
419 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
420 out.write(j.toString());
424 response.setCharacterEncoding("UTF-8");
425 request.setCharacterEncoding("UTF-8");
426 PrintWriter out = response.getWriter();
427 out.write(e.getMessage());
432 public void PrePopulateBRMSParamPolicyData(PolicyAdapter policyAdapter) {
433 attributeList = new ArrayList<Object>();
434 dynamicLayoutMap = new HashMap<String, String>();
435 if (policyAdapter.getPolicyData() instanceof PolicyType) {
436 PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
437 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
438 // policy name value is the policy name without any prefix and
440 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") +11, policyAdapter.getPolicyName().lastIndexOf("."));
441 if (logger.isDebugEnabled()) {
442 logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
444 policyAdapter.setPolicyName(policyNameValue);
445 String description = "";
447 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
449 description = policy.getDescription();
451 policyAdapter.setPolicyDescription(description);
453 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
454 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
455 for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
456 if(attributeAssignment.getAttributeId().startsWith("key:")){
457 Map<String, String> attribute = new HashMap<String, String>();
458 String key = attributeAssignment.getAttributeId().replace("key:", "");
459 attribute.put("key", key);
460 JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
461 String value = (String) attributevalue.getValue().getContent().get(0);
462 attribute.put("value", value);
463 attributeList.add(attribute);
466 policyAdapter.setAttributes(attributeList);
468 String ruleConfigName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + ".txt";
469 policyAdapter.setConfigBodyPath(ruleConfigName);
470 paramUIGenerate(policyAdapter);
471 // Get the target data under policy.
472 policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
473 if(policyAdapter.getDynamicLayoutMap().size() > 0){
474 LinkedHashMap<String,String> drlRule = new LinkedHashMap<String, String>();
475 for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
476 drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue).toString());
478 policyAdapter.setRuleData(drlRule);
480 TargetType target = policy.getTarget();
481 if (target != null) {
482 // Under target we have AnyOFType
483 List<AnyOfType> anyOfList = target.getAnyOf();
484 if (anyOfList != null) {
485 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
486 while (iterAnyOf.hasNext()) {
487 AnyOfType anyOf = iterAnyOf.next();
488 // Under AnyOFType we have AllOFType
489 List<AllOfType> allOfList = anyOf.getAllOf();
490 if (allOfList != null) {
491 Iterator<AllOfType> iterAllOf = allOfList.iterator();
493 while (iterAllOf.hasNext()) {
494 AllOfType allOf = iterAllOf.next();
495 // Under AllOFType we have Match
496 List<MatchType> matchList = allOf.getMatch();
497 if (matchList != null) {
498 Iterator<MatchType> iterMatch = matchList.iterator();
499 while (iterMatch.hasNext()) {
500 MatchType match = iterMatch.next();
502 // Under the match we have attributevalue and
503 // attributeDesignator. So,finally down to the actual attribute.
505 AttributeValueType attributeValue = match.getAttributeValue();
506 String value = (String) attributeValue.getContent().get(0);
509 policyAdapter.setRiskType(value);
513 policyAdapter.setRiskLevel(value);
517 policyAdapter.setGuard(value);
519 if (index == 6 && !value.contains("NA")){
520 String newDate = convertDate(value, true);
521 policyAdapter.setTtlDate(newDate);
535 private String convertDate(String dateTTL, boolean portalType) {
536 String formateDate = null;
541 parts = dateTTL.split("-");
542 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
544 date = dateTTL.split("T");
545 parts = date[0].split("-");
546 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
550 // This method generates the UI from rule configuration
551 private void paramUIGenerate(PolicyAdapter policyAdapter) {
552 String fileLocation = null;
553 String fileName = policyAdapter.getConfigBodyPath();
554 if (fileName != null) {
555 fileLocation = PolicyController.getConfigHome();
557 if (logger.isDebugEnabled()) {
558 logger.debug("Attempting to read file from the location: " + fileLocation);
560 if (fileLocation == null) {
561 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error with the FileName: " + fileName);
564 File dir = new File(fileLocation);
565 File[] listOfFiles = dir.listFiles();
566 for (File file : listOfFiles) {
567 if (file.isFile() && file.getName().contains(fileName)
568 && file.toString().endsWith(".txt")) {
571 try (BufferedReader br = new BufferedReader(new FileReader(file))) {
572 StringBuilder sb = new StringBuilder();
573 String line = br.readLine();
574 while (line != null) {
577 line = br.readLine();
580 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage());
583 Boolean flag = false;
584 Boolean comment = false;
585 for (String line : Files.readAllLines(Paths.get(file.toString()))) {
586 if (line.isEmpty() || line.startsWith("//")) {
589 if(line.contains("<$%BRMSParamTemplate=")){
590 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
591 value = value.replace("<$%BRMSParamTemplate=", "");
592 policyAdapter.setRuleName(value);
594 if (line.startsWith("/*")) {
598 if (line.contains("//")) {
599 if(!(line.contains("http://") || line.contains("https://"))){
600 line = line.split("\\/\\/")[0];
603 if (line.contains("/*")) {
605 if (line.contains("*/")) {
608 line = line.split("\\/\\*")[0]
609 + line.split("\\*\\/")[1].replace(
611 } catch (Exception e) {
612 line = line.split("\\/\\*")[0];
615 line = line.split("\\/\\*")[0];
618 if (line.contains("*/")) {
621 line = line.split("\\*\\/")[1]
623 } catch (Exception e) {
631 params = params + line;
633 if (line.contains("rule \"Params\"")) {
634 params = params + line;
637 if (line.contains("end") && flag) {
641 params = params.replaceAll("\\s+", "").replace("rule\"Params\"salience1000whenthenParamsparams=newParams();","")
642 .replace("insert(params);end", "")
643 .replace("params.set", "");
644 String[] components = params.split(";");
645 if(components!= null && components.length > 0){
646 for (int i = 0; i < components.length; i++) {
648 String caption = components[i].substring(0,
649 components[i].indexOf("("));
650 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
651 if (components[i].contains("(\"")) {
652 value = components[i]
653 .substring(components[i].indexOf("(\""),
654 components[i].indexOf("\")"))
655 .replace("(\"", "").replace("\")", "");
657 value = components[i]
658 .substring(components[i].indexOf("("),
659 components[i].indexOf(")"))
660 .replace("(", "").replace(")", "");
662 dynamicLayoutMap.put(caption, value);
666 } catch (FileNotFoundException e) {
667 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage());
668 } catch (IOException e1) {
669 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e1.getMessage());
676 @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
677 public ModelAndView setViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{
679 ObjectMapper mapper = new ObjectMapper();
680 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
681 JsonNode root = mapper.readTree(request.getReader());
682 PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class);
686 body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
687 "<$%BRMSParamTemplate=" + policyData.getRuleName() + "%$> \n */ \n";
688 body = body + findRule((String) policyData.getRuleName()) + "\n";
689 String generatedRule = "rule \"Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();";
691 if(policyData.getRuleData().size() > 0){
692 for(Object keyValue: policyData.getRuleData().keySet()){
693 String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
694 if (keyValue.equals("String")) {
695 generatedRule = generatedRule + "\n\t\tparams.set"
697 + policyData.getRuleData().get(keyValue).toString() + "\");";
699 generatedRule = generatedRule + "\n\t\tparams.set"
701 + policyData.getRuleData().get(keyValue).toString() + ");";
705 generatedRule = generatedRule
706 + "\n\t\tinsert(params);\nend";
707 logger.info("New rule generated with :" + generatedRule);
708 body = body + generatedRule;
709 response.setCharacterEncoding("UTF-8");
710 response.setContentType("application / json");
711 request.setCharacterEncoding("UTF-8");
713 PrintWriter out = response.getWriter();
714 String responseString = mapper.writeValueAsString(body);
715 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
716 out.write(j.toString());
718 } catch (Exception e) {
719 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);