Fix console issues
[policy/engine.git] / POLICY-SDK-APP / src / main / java / org / onap / policy / controller / CreateBRMSParamController.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP 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.onap.policy.controller;
22
23 import java.io.PrintWriter;
24 import java.util.ArrayList;
25 import java.util.Arrays;
26 import java.util.HashMap;
27 import java.util.Iterator;
28 import java.util.LinkedHashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Set;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
37 import javax.xml.bind.JAXBElement;
38
39 import org.json.JSONObject;
40 import org.onap.policy.common.logging.flexlogger.FlexLogger;
41 import org.onap.policy.common.logging.flexlogger.Logger;
42 import org.onap.policy.rest.adapter.PolicyRestAdapter;
43 import org.onap.policy.rest.dao.CommonClassDao;
44 import org.onap.policy.rest.jpa.BRMSParamTemplate;
45 import org.onap.policy.rest.jpa.PolicyEntity;
46 import org.onap.policy.xacml.api.XACMLErrorConstants;
47 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.stereotype.Controller;
50 import org.springframework.web.bind.annotation.RequestMapping;
51
52 import com.fasterxml.jackson.databind.DeserializationFeature;
53 import com.fasterxml.jackson.databind.JsonNode;
54 import com.fasterxml.jackson.databind.ObjectMapper;
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.MatchType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
67
68 @Controller
69 @RequestMapping("/")
70 public class CreateBRMSParamController extends RestrictedBaseController {
71         private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class);
72
73         private static CommonClassDao commonClassDao;
74
75         public static CommonClassDao getCommonClassDao() {
76                 return commonClassDao;
77         }
78
79         public static void setCommonClassDao(CommonClassDao commonClassDao) {
80                 CreateBRMSParamController.commonClassDao = commonClassDao;
81         }
82         
83         @Autowired
84         private CreateBRMSParamController(CommonClassDao commonClassDao){
85                 CreateBRMSParamController.commonClassDao = commonClassDao;
86         }
87
88         public CreateBRMSParamController(){}
89         protected PolicyRestAdapter policyAdapter = null; 
90
91         private HashMap<String, String> dynamicLayoutMap;
92         
93         private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
94         private static String string = "String";
95
96
97         @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
98         public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){
99                 try{
100                         dynamicLayoutMap = new HashMap<>();
101                         ObjectMapper mapper = new ObjectMapper();
102                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
103                         JsonNode root = mapper.readTree(request.getReader());
104                         String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", ""));
105                         generateUI(rule);
106                         response.setCharacterEncoding(PolicyController.getCharacterencoding());
107                         response.setContentType(PolicyController.getContenttype());
108                         request.setCharacterEncoding(PolicyController.getCharacterencoding());
109
110                         PrintWriter out = response.getWriter();
111                         String responseString = mapper.writeValueAsString(dynamicLayoutMap);
112                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
113                         out.write(j.toString());
114                 }catch(Exception e){
115                         policyLogger.error("Exception Occured while getting BRMS Rule data" , e);
116                 }
117         }
118
119         protected String findRule(String ruleTemplate) {
120                 List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate);
121                 if(datas != null && !datas.isEmpty()){
122                         BRMSParamTemplate  bRMSParamTemplate = (BRMSParamTemplate) datas.get(0);
123                         return bRMSParamTemplate.getRule();
124                 }
125                 return null;
126         }
127
128         protected void generateUI(String rule) {
129                 if(rule!=null){
130                         try {
131                                 StringBuilder params = new StringBuilder("");
132                                 Boolean flag = false;
133                                 Boolean comment = false;
134                                 String lines[] = rule.split("\n");
135                                 for(String line : lines){
136                                         if (line.isEmpty() || line.startsWith("//")) {
137                                                 continue;
138                                         }
139                                         if (line.startsWith("/*")) {
140                                                 comment = true;
141                                                 continue;
142                                         }
143                                         if (line.contains("//")) {
144                                                 line = line.split("\\/\\/")[0];
145                                         }
146                                         if (line.contains("/*")) {
147                                                 comment = true;
148                                                 if (line.contains("*/")) {
149                                                         try {
150                                                                 comment = false;
151                                                                 line = line.split("\\/\\*")[0]
152                                                                                 + line.split("\\*\\/")[1].replace("*/", "");
153                                                         } catch (Exception e) {
154                                                                 policyLogger.info("Just for Logging"+e);
155                                                                 line = line.split("\\/\\*")[0];
156                                                         }
157                                                 } else {
158                                                         line = line.split("\\/\\*")[0];
159                                                 }
160                                         }
161                                         if (line.contains("*/")) {
162                                                 comment = false;
163                                                 try {
164                                                         line = line.split("\\*\\/")[1].replace("*/", "");
165                                                 } catch (Exception e) {
166                                                         policyLogger.info("Just for Logging"+e);
167                                                         line = "";
168                                                 }
169                                         }
170                                         if (comment) {
171                                                 continue;
172                                         }
173                                         if (flag) {
174                                                 params.append(line);
175                                         }
176                                         if (line.contains("declare Params")) {
177                                                 params.append(line);
178                                                 flag = true;
179                                         }
180                                         if (line.contains("end") && flag) {
181                                                 break;
182                                         }
183                                 }
184                                 params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
185                                 String[] components = params.toString().split(":");
186                                 String caption = "";
187                                 for (int i = 0; i < components.length; i++) {
188                                         String type = "";
189                                         if (i == 0) {
190                                                 caption = components[i];
191                                         }
192                                         if("".equals(caption)){
193                                                 break;
194                                         }
195                                         String nextComponent = "";
196                                         try {
197                                                 nextComponent = components[i + 1];
198                                         } catch (Exception e) {
199                                                 policyLogger.info("Just for Logging"+e);
200                                                 nextComponent = components[i];
201                                         }
202                                         if (nextComponent.startsWith(string)) {
203                                                 type = "String";
204                                                 createField(caption, type);
205                                                 caption = nextComponent.replace(string, "");
206                                         } else if (nextComponent.startsWith("int")) {
207                                                 type = "int";
208                                                 createField(caption, type);
209                                                 caption = nextComponent.replace("int", "");
210                                         }
211                                 }
212                         } catch (Exception e) {
213                                 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
214                         }
215                 }
216         }
217         
218         private void createField(String caption, String type) {
219                 dynamicLayoutMap.put(caption, type);
220         }
221
222         /*
223          * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter.
224          * Which is used to bind the data in GUI
225          */
226         public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
227                 dynamicLayoutMap = new HashMap<>();
228                 if (policyAdapter.getPolicyData() instanceof PolicyType) {
229                         PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
230                         policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
231                         // policy name value is the policy name without any prefix and
232                         // Extensions.
233                         String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
234                         if (policyLogger.isDebugEnabled()) {
235                                 policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
236                         }
237                         policyAdapter.setPolicyName(policyNameValue);
238                         String description = "";
239                         try{
240                                 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
241                         }catch(Exception e){
242                                 policyLogger.info("Just for Logging"+e);
243                                 description = policy.getDescription();
244                         }
245                         policyAdapter.setPolicyDescription(description);
246                         setDataAdapterFromAdviceExpressions(policy, policyAdapter);
247                         paramUIGenerate(policyAdapter, entity);
248                         // Get the target data under policy.
249                         policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
250                         if(policyAdapter.getDynamicLayoutMap().size() > 0){
251                                 LinkedHashMap<String,String> drlRule = new LinkedHashMap<>();
252                                 for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
253                                         drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue));
254                                 }
255                                 policyAdapter.setRuleData(drlRule);
256                         }       
257                         TargetType target = policy.getTarget();
258                         if (target != null) {
259                                 setDataToAdapterFromTarget(target, policyAdapter);
260                         }
261                 }               
262         }
263         
264         private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){
265                 ArrayList<Object> attributeList = new ArrayList<>();
266                 // Set Attributes. 
267                 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
268                 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
269                         for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
270                                 if(attributeAssignment.getAttributeId().startsWith("key:")){
271                                         Map<String, String> attribute = new HashMap<>();
272                                         String key = attributeAssignment.getAttributeId().replace("key:", "");
273                                         attribute.put("key", key);
274                                         @SuppressWarnings("unchecked")
275                                         JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
276                                         String value = (String) attributevalue.getValue().getContent().get(0);
277                                         attribute.put("value", value);
278                                         attributeList.add(attribute);
279                                 }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
280                                         ArrayList<String> dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
281                                         if(dependencies.contains("")){
282                                                 dependencies.remove("");
283                                         }
284                                         policyAdapter.setBrmsDependency(dependencies);
285                                 }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
286                                         policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
287                                 }
288                         }
289                         policyAdapter.setAttributes(attributeList);
290                 }
291         }
292         
293         private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){
294                 // Under target we have AnyOFType
295                 List<AnyOfType> anyOfList = target.getAnyOf();
296                 if (anyOfList != null) {
297                         Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
298                         while (iterAnyOf.hasNext()) {
299                                 AnyOfType anyOf = iterAnyOf.next();
300                                 // Under AnyOFType we have AllOFType
301                                 List<AllOfType> allOfList = anyOf.getAllOf();
302                                 if (allOfList != null) {
303                                         Iterator<AllOfType> iterAllOf = allOfList.iterator();
304                                         while (iterAllOf.hasNext()) {
305                                                 AllOfType allOf = iterAllOf.next();
306                                                 // Under AllOFType we have Match
307                                                 List<MatchType> matchList = allOf.getMatch();
308                                                 if (matchList != null) {
309                                                         setDataToAdapterFromMatchList(matchList, policyAdapter);
310                                                 }
311                                         }
312                                 }
313                         }
314                 }
315         }
316         
317         private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){
318                 Iterator<MatchType> iterMatch = matchList.iterator();
319                 while (iterMatch.hasNext()) {
320                         MatchType match = iterMatch.next();
321                         //
322                         // Under the match we have attribute value and
323                         // attributeDesignator. So,finally down to the actual attribute.
324                         //
325                         AttributeValueType attributeValue = match.getAttributeValue();
326                         String value = (String) attributeValue.getContent().get(0);
327                         AttributeDesignatorType designator = match.getAttributeDesignator();
328                         String attributeId = designator.getAttributeId();
329
330                         if ("RiskType".equals(attributeId)){
331                                 policyAdapter.setRiskType(value);
332                         }
333                         if ("RiskLevel".equals(attributeId)){
334                                 policyAdapter.setRiskLevel(value);
335                         }
336                         if ("guard".equals(attributeId)){
337                                 policyAdapter.setGuard(value);
338                         }
339                         if ("TTLDate".equals(attributeId) && !value.contains("NA")){
340                                 String newDate = convertDate(value, true);
341                                 policyAdapter.setTtlDate(newDate);
342                         }
343                 }
344         }
345
346         private String convertDate(String dateTTL, boolean portalType) {
347                 String formateDate = null;
348                 String[] date;
349                 String[] parts;
350                 
351                 if (portalType){
352                         parts = dateTTL.split("-");
353                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
354                 } else {
355                         date  = dateTTL.split("T");
356                         parts = date[0].split("-");
357                         formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
358                 }
359                 return formateDate;
360         }
361         // This method generates the UI from rule configuration
362         public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
363                 String data = entity.getConfigurationData().getConfigBody();
364                 if(data != null){
365                         try {   
366                                 StringBuilder params = new StringBuilder("");
367                                 Boolean flag = false;
368                                 Boolean comment = false;
369                                 for (String line : data.split("\n")) {
370                                         if (line.isEmpty() || line.startsWith("//")) {
371                                                 continue;
372                                         }
373                                         if(line.contains(brmsTemplateVlaue)){
374                                                 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
375                                                 value = value.replace(brmsTemplateVlaue, "");
376                                                 policyAdapter.setRuleName(value);
377                                         }
378                                         if (line.startsWith("/*")) {
379                                                 comment = true;
380                                                 continue;
381                                         }
382                                         if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){
383                                                 line = line.split("\\/\\/")[0];
384                                         }
385                                         if (line.contains("/*")) {
386                                                 comment = true;
387                                                 if (line.contains("*/")) {
388                                                         try {
389                                                                 comment = false;
390                                                                 line = line.split("\\/\\*")[0]
391                                                                                 + line.split("\\*\\/")[1].replace(
392                                                                                                 "*/", "");
393                                                         } catch (Exception e) {
394                                                                 policyLogger.info("Just for Logging"+e);
395                                                                 line = line.split("\\/\\*")[0];
396                                                         }
397                                                 } else {
398                                                         line = line.split("\\/\\*")[0];
399                                                 }
400                                         }
401                                         if (line.contains("*/")) {
402                                                 comment = false;
403                                                 try {
404                                                         line = line.split("\\*\\/")[1]
405                                                                         .replace("*/", "");
406                                                 } catch (Exception e) {
407                                                         policyLogger.info("Just for Logging"+e);
408                                                         line = "";
409                                                 }
410                                         }
411                                         if (comment) {
412                                                 continue;
413                                         }
414                                         if (flag) {
415                                                 params.append(line);
416                                         }
417                                         if (line.contains("rule") && line.contains(".Params\"")) {
418                                                 params.append(line);
419                                                 flag = true;
420                                         }
421                                         if (line.contains("end") && flag) {
422                                                 break;
423                                         }
424                                 }
425                                 params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8));
426                                 params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
427                         .replace("insert(params);end", "")
428                         .replace("params.set", ""));
429                                 String[] components = params.toString().split("\\);");
430                                 if(components!= null && components.length > 0){
431                                         for (int i = 0; i < components.length; i++) {
432                                                 String value = null;
433                                                 components[i] = components[i]+")";
434                                                 String caption = components[i].substring(0,
435                                                                 components[i].indexOf('('));
436                                                 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
437                                                 if (components[i].contains("(\"")) {
438                                                         value = components[i]
439                                                                         .substring(components[i].indexOf("(\""),
440                                                                                         components[i].indexOf("\")"))
441                                                                         .replace("(\"", "").replace("\")", "");
442                                                 } else {
443                                                         value = components[i]
444                                                                         .substring(components[i].indexOf('('),
445                                                                                         components[i].indexOf(')'))
446                                                                         .replace("(", "").replace(")", "");
447                                                 }
448                                                 dynamicLayoutMap.put(caption, value);
449
450                                         }
451                                 }
452                         } catch (Exception e) {
453                                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
454                         } 
455                 }
456                 
457         }
458
459         // set View Rule
460         @SuppressWarnings("unchecked")
461         @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
462         public void setViewRule(HttpServletRequest request, HttpServletResponse response){
463                 try {
464                         ObjectMapper mapper = new ObjectMapper();
465                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
466                         JsonNode root = mapper.readTree(request.getReader());
467                         PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
468                         policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
469                         if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){
470                                 policyData.setEditPolicy(true);
471                         }
472
473                         String body = "";
474
475                         body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
476                                         brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
477                         body = body + findRule((String) policyData.getRuleName()) + "\n";
478                         StringBuilder generatedRule = new StringBuilder();
479                         generatedRule.append("rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();");
480
481                         if(policyData.getRuleData().size() > 0){ 
482                                 for(Object keyValue: policyData.getRuleData().keySet()){ 
483                                         String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1); 
484                                         if (string.equals(keyValue)) { 
485                                                 generatedRule.append("\n\t\tparams.set" 
486                                                                 + key + "(\"" 
487                                                                 + policyData.getRuleData().get(keyValue).toString() + "\");"); 
488                                         } else { 
489                                                 generatedRule.append("\n\t\tparams.set" 
490                                                                 + key + "(" 
491                                                                 + policyData.getRuleData().get(keyValue).toString() + ");"); 
492                                         } 
493                                 } 
494                         }
495                         generatedRule.append("\n\t\tinsert(params);\nend");
496                         policyLogger.info("New rule generated with :" + generatedRule.toString());
497                         body = body + generatedRule.toString();
498                         // Expand the body. 
499                         Map<String,String> copyMap=new HashMap<>();
500                         copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
501                         copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
502                         copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
503                         copyMap.put("policyVersion", "1");
504                         //Finding all the keys in the Map data-structure.
505                         Set<String> keySet= copyMap.keySet();
506                         Iterator<String> iterator = keySet.iterator(); 
507                         Pattern p;
508                         Matcher m;
509                         while(iterator.hasNext()) {
510                                 //Converting the first character of the key into a lower case. 
511                                 String input= iterator.next();
512                                 String output  = Character.toLowerCase(input.charAt(0)) +
513                                                 (input.length() > 1 ? input.substring(1) : "");
514                                 //Searching for a pattern in the String using the key. 
515                                 p=Pattern.compile("\\$\\{"+output+"\\}");   
516                                 m=p.matcher(body);
517                                 //Replacing the value with the inputs provided by the user in the editor. 
518                                 body=m.replaceAll(copyMap.get(input));
519                         }
520                         response.setCharacterEncoding("UTF-8");
521                         response.setContentType("application / json");
522                         request.setCharacterEncoding("UTF-8");
523
524                         PrintWriter out = response.getWriter();
525                         String responseString = mapper.writeValueAsString(body);
526                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
527                         out.write(j.toString());
528                 } catch (Exception e) {
529                         policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
530                 }       
531         }
532 }