Initial OpenECOMP policy/engine commit
[policy/engine.git] / ecomp-sdk-app / src / main / java / org / openecomp / policy / controller / CreateBRMSParamController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ECOMP Policy Engine
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.policy.controller;
22
23
24 import java.io.BufferedReader;
25 import java.io.File;
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;
42 import java.util.Map;
43 import java.util.UUID;
44
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47 import javax.xml.bind.JAXBElement;
48
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;
67
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;
75
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;
86
87 import org.openecomp.policy.common.logging.flexlogger.FlexLogger; 
88 import org.openecomp.policy.common.logging.flexlogger.Logger;
89
90 @Controller
91 @RequestMapping("/")
92 public class CreateBRMSParamController extends RestrictedBaseController {
93         private static final Logger logger = FlexLogger.getLogger(CreateBRMSParamController.class);
94
95         private static RuleAlgorithmsDao ruleAlgorithmsDao;
96         private static BRMSParamTemplateDao bRMSParamTemplateDao;
97         private static PolicyVersionDao policyVersionDao;
98         private static WatchPolicyNotificationDao policyNotificationDao;
99
100         @Autowired
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;
107         }
108
109         public CreateBRMSParamController(){}
110         protected PolicyAdapter policyAdapter = null;
111         private ArrayList<Object> attributeList;
112         private String ruleID = "";
113
114         private HashMap<String, String> dynamicLayoutMap;
115
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());
119         }
120
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("^\"|\"$", ""));
128                 generateUI(rule);
129                 response.setCharacterEncoding("UTF-8");
130                 response.setContentType("application / json");
131                 request.setCharacterEncoding("UTF-8");
132
133                 PrintWriter out = response.getWriter();
134                 String responseString = mapper.writeValueAsString(dynamicLayoutMap);
135                 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
136                 out.write(j.toString());
137                 return null;
138         }
139
140         protected String findRule(String ruleTemplate) {
141                 for (BRMSParamTemplate bRMSParamTemplate: bRMSParamTemplateDao.getBRMSParamTemplateData()){
142                         if(bRMSParamTemplate.getRuleName().equals(ruleTemplate)){
143                                 return bRMSParamTemplate.getRule();
144                         }
145                 }
146                 return null;
147         }
148
149         protected void generateUI(String rule) {
150                 if(rule!=null){
151                         try {
152                                 String params = "";
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("//")) {
158                                                 continue;
159                                         }
160                                         if (line.startsWith("/*")) {
161                                                 comment = true;
162                                                 continue;
163                                         }
164                                         if (line.contains("//")) {
165                                                 line = line.split("\\/\\/")[0];
166                                         }
167                                         if (line.contains("/*")) {
168                                                 comment = true;
169                                                 if (line.contains("*/")) {
170                                                         try {
171                                                                 comment = false;
172                                                                 line = line.split("\\/\\*")[0]
173                                                                                 + line.split("\\*\\/")[1].replace("*/", "");
174                                                         } catch (Exception e) {
175                                                                 line = line.split("\\/\\*")[0];
176                                                         }
177                                                 } else {
178                                                         line = line.split("\\/\\*")[0];
179                                                 }
180                                         }
181                                         if (line.contains("*/")) {
182                                                 comment = false;
183                                                 try {
184                                                         line = line.split("\\*\\/")[1].replace("*/", "");
185                                                 } catch (Exception e) {
186                                                         line = "";
187                                                 }
188                                         }
189                                         if (comment) {
190                                                 continue;
191                                         }
192                                         if (flag) {
193                                                 params = params + line;
194                                         }
195                                         if (line.contains("declare Params")) {
196                                                 params = params + line;
197                                                 flag = true;
198                                         }
199                                         if (line.contains("end") && flag) {
200                                                 break;
201                                         }
202                                 }
203                                 params = params.replace("declare Params", "").replace("end", "")
204                                                 .replaceAll("\\s+", "");
205                                 String[] components = params.split(":");
206                                 String caption = "";
207                                 for (int i = 0; i < components.length; i++) {
208                                         String type = "";
209                                         if (i == 0) {
210                                                 caption = components[i];
211                                         }
212                                         if(caption.equals("")){
213                                                 break;
214                                         }
215                                         String nextComponent = "";
216                                         try {
217                                                 nextComponent = components[i + 1];
218                                         } catch (Exception e) {
219                                                 nextComponent = components[i];
220                                         }
221                                         if (nextComponent.startsWith("String")) {
222                                                 type = "String";
223                                                 createField(caption, type);
224                                                 caption = nextComponent.replace("String", "");
225                                         } else if (nextComponent.startsWith("int")) {
226                                                 type = "int";
227                                                 createField(caption, type);
228                                                 caption = nextComponent.replace("int", "");
229                                         }
230                                 }
231                         } catch (Exception e) {
232                                 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
233                         }
234                 }
235         }
236
237         private String convertDate(String dateTTL) {
238                 String formateDate = null;
239                 String[] date  = dateTTL.split("T");
240                 String[] parts = date[0].split("-");
241                 
242                 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
243                 return formateDate;
244         }
245         
246         private void createField(String caption, String type) {
247                 dynamicLayoutMap.put(caption, type);
248         }
249
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{
252                 try {
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);
259
260                         if (policyData.getTtlDate()==null){
261                                 policyData.setTtlDate("NA");
262                         }else{
263                                 String dateTTL = policyData.getTtlDate();
264                                 String newDate = convertDate(dateTTL);
265                                 policyData.setTtlDate(newDate);
266                         }
267                         
268                         if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
269                                 policyData.isEditPolicy = true;
270                         }
271                         if(root.get("policyData").get("model").get("path").size() != 0){
272                                 String dirName = "";
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;
275                                 }
276                                 policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator)));
277                         }else{
278                                 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
279                         }
280                         int version = 0;
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();
292                                         }
293                                 }
294                         }               
295                         if(highestVersion != 0){
296                                 version = highestVersion;
297                                 descriptionVersion = highestVersion +1;         
298                         }else{
299                                 version = 1;
300                                 descriptionVersion = 1;
301                         }
302
303                         //set policy adapter values for Building JSON object containing policy data
304                         String createdBy = "";
305                         String modifiedBy = userId;
306                         if(descriptionVersion == 1){
307                                 createdBy = userId;
308                         }else{
309                                 String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml";
310                                 File policyPath = new File(policyName);
311                                 try {
312                                         createdBy =     XACMLPolicyScanner.getCreatedBy(policyPath.toPath());
313                                 } catch (IOException e) {
314                                         createdBy = "guest";
315                                 }
316                         }
317
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());
327                                         break;
328                                 }
329                         }
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);   
336                                         }
337                                 }
338                         }
339
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());
353                                 }
354                         }
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);
363                         } else {
364                                 //send it for policy creation
365                                 policyData.setVersion(String.valueOf(version));
366                                 policyData.setHighestVersion(version);
367                                 successMap = engine.createPolicyRequest(policyData);
368
369                         }
370
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();
378                                 if(file != null){
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);
398                                                                 }
399                                                         }
400                                                 }
401                                         }else{
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);
409                                         }
410                                 }
411                         }
412
413                         response.setCharacterEncoding("UTF-8");
414                         response.setContentType("application / json");
415                         request.setCharacterEncoding("UTF-8");
416
417                         PrintWriter out = response.getWriter();
418                         String responseString = mapper.writeValueAsString(successMap);
419                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
420                         out.write(j.toString());
421                         return null;
422                 }
423                 catch (Exception e){
424                         response.setCharacterEncoding("UTF-8");
425                         request.setCharacterEncoding("UTF-8");
426                         PrintWriter out = response.getWriter();
427                         out.write(e.getMessage());
428                 }
429                 return null;
430         }
431
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
439                         // Extensions.
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());
443                         }
444                         policyAdapter.setPolicyName(policyNameValue);
445                         String description = "";
446                         try{
447                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
448                         }catch(Exception e){
449                                 description = policy.getDescription();
450                         }
451                         policyAdapter.setPolicyDescription(description);
452                         // Set Attributes. 
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);
464                                         }
465                                 }
466                                 policyAdapter.setAttributes(attributeList);
467                         }
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());
477                                 }
478                                 policyAdapter.setRuleData(drlRule);
479                         }       
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();
492                                                         int index = 0;
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();
501                                                                                 //
502                                                                                 // Under the match we have attributevalue and
503                                                                                 // attributeDesignator. So,finally down to the actual attribute.
504                                                                                 //
505                                                                                 AttributeValueType attributeValue = match.getAttributeValue();
506                                                                                 String value = (String) attributeValue.getContent().get(0);
507
508                                                                                 if (index ==  3){
509                                                                                         policyAdapter.setRiskType(value);
510                                                                                 }
511
512                                                                                 if (index ==  4){
513                                                                                         policyAdapter.setRiskLevel(value);
514                                                                                 }
515                                                                                 
516                                                                                 if (index ==  5){
517                                                                                         policyAdapter.setGuard(value);
518                                                                                 }
519                                                                                 if (index == 6 && !value.contains("NA")){
520                                                                                         String newDate = convertDate(value, true);
521                                                                                         policyAdapter.setTtlDate(newDate);
522                                                                                 }
523
524                                                                                 index++;
525                                                                         }
526                                                                 }
527                                                         }
528                                                 }
529                                         }
530                                 }
531                         }
532                 }               
533         }
534
535         private String convertDate(String dateTTL, boolean portalType) {
536                 String formateDate = null;
537                 String[] date;
538                 String[] parts;
539                 
540                 if (portalType){
541                         parts = dateTTL.split("-");
542                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
543                 } else {
544                         date  = dateTTL.split("T");
545                         parts = date[0].split("-");
546                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
547                 }
548                 return formateDate;
549         }
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();
556                 }
557                 if (logger.isDebugEnabled()) {
558                         logger.debug("Attempting to read file from the location: " + fileLocation);
559                 }
560                 if (fileLocation == null) {
561                         logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error with the FileName: " + fileName);
562                         return;
563                 }
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")) {
569                                 // Reading the file
570                                 try {
571                                         try (BufferedReader br = new BufferedReader(new FileReader(file))) {
572                                                 StringBuilder sb = new StringBuilder();
573                                                 String line = br.readLine();
574                                                 while (line != null) {
575                                                         sb.append(line);
576                                                         sb.append("\n");
577                                                         line = br.readLine();
578                                                 }
579                                         }catch(Exception e){
580                                                 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage());
581                                         }
582                                         String params = "";
583                                         Boolean flag = false;
584                                         Boolean comment = false;
585                                         for (String line : Files.readAllLines(Paths.get(file.toString()))) {
586                                                 if (line.isEmpty() || line.startsWith("//")) {
587                                                         continue;
588                                                 }
589                                                 if(line.contains("<$%BRMSParamTemplate=")){
590                                                         String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
591                                                         value = value.replace("<$%BRMSParamTemplate=", "");
592                                                         policyAdapter.setRuleName(value);
593                                                 }
594                                                 if (line.startsWith("/*")) {
595                                                         comment = true;
596                                                         continue;
597                                                 }
598                                                 if (line.contains("//")) {
599                                                         if(!(line.contains("http://") || line.contains("https://"))){
600                                                                 line = line.split("\\/\\/")[0];
601                                                         }
602                                                 }
603                                                 if (line.contains("/*")) {
604                                                         comment = true;
605                                                         if (line.contains("*/")) {
606                                                                 try {
607                                                                         comment = false;
608                                                                         line = line.split("\\/\\*")[0]
609                                                                                         + line.split("\\*\\/")[1].replace(
610                                                                                                         "*/", "");
611                                                                 } catch (Exception e) {
612                                                                         line = line.split("\\/\\*")[0];
613                                                                 }
614                                                         } else {
615                                                                 line = line.split("\\/\\*")[0];
616                                                         }
617                                                 }
618                                                 if (line.contains("*/")) {
619                                                         comment = false;
620                                                         try {
621                                                                 line = line.split("\\*\\/")[1]
622                                                                                 .replace("*/", "");
623                                                         } catch (Exception e) {
624                                                                 line = "";
625                                                         }
626                                                 }
627                                                 if (comment) {
628                                                         continue;
629                                                 }
630                                                 if (flag) {
631                                                         params = params + line;
632                                                 }
633                                                 if (line.contains("rule \"Params\"")) {
634                                                         params = params + line;
635                                                         flag = true;
636                                                 }
637                                                 if (line.contains("end") && flag) {
638                                                         break;
639                                                 }
640                                         }
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++) {
647                                                         String value = null;
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("\")", "");
656                                                         } else {
657                                                                 value = components[i]
658                                                                                 .substring(components[i].indexOf("("),
659                                                                                                 components[i].indexOf(")"))
660                                                                                 .replace("(", "").replace(")", "");
661                                                         }
662                                                         dynamicLayoutMap.put(caption, value);
663
664                                                 }
665                                         }
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());
670                                 }
671                         }
672                 }
673         }
674
675         // set View Rule
676         @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
677         public ModelAndView setViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{
678                 try {
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);
683
684                         String body = "";
685
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();";
690
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" 
696                                                                 + key + "(\"" 
697                                                                 + policyData.getRuleData().get(keyValue).toString() + "\");"; 
698                                         } else { 
699                                                 generatedRule = generatedRule + "\n\t\tparams.set" 
700                                                                 + key + "(" 
701                                                                 + policyData.getRuleData().get(keyValue).toString() + ");"; 
702                                         } 
703                                 } 
704                         }
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");
712
713                         PrintWriter out = response.getWriter();
714                         String responseString = mapper.writeValueAsString(body);
715                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
716                         out.write(j.toString());
717                         return null;
718                 } catch (Exception e) {
719                         logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
720                 }
721                 return null;    
722         }
723 }