fc7cb60e57ed5ef7463a09dedae5cdc149ccaaa3
[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                                 PolicyController controller = new PolicyController();
341                                 String newDate = controller.convertDate(value);
342                                 policyAdapter.setTtlDate(newDate);
343                         }
344                 }
345         }
346
347         // This method generates the UI from rule configuration
348         public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
349                 String data = entity.getConfigurationData().getConfigBody();
350                 if(data != null){
351                         try {   
352                                 StringBuilder params = new StringBuilder("");
353                                 Boolean flag = false;
354                                 Boolean comment = false;
355                                 for (String line : data.split("\n")) {
356                                         if (line.isEmpty() || line.startsWith("//")) {
357                                                 continue;
358                                         }
359                                         if(line.contains(brmsTemplateVlaue)){
360                                                 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
361                                                 value = value.replace(brmsTemplateVlaue, "");
362                                                 policyAdapter.setRuleName(value);
363                                         }
364                                         if (line.startsWith("/*")) {
365                                                 comment = true;
366                                                 continue;
367                                         }
368                                         if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){
369                                                 line = line.split("\\/\\/")[0];
370                                         }
371                                         if (line.contains("/*")) {
372                                                 comment = true;
373                                                 if (line.contains("*/")) {
374                                                         try {
375                                                                 comment = false;
376                                                                 line = line.split("\\/\\*")[0]
377                                                                                 + line.split("\\*\\/")[1].replace(
378                                                                                                 "*/", "");
379                                                         } catch (Exception e) {
380                                                                 policyLogger.info("Just for Logging"+e);
381                                                                 line = line.split("\\/\\*")[0];
382                                                         }
383                                                 } else {
384                                                         line = line.split("\\/\\*")[0];
385                                                 }
386                                         }
387                                         if (line.contains("*/")) {
388                                                 comment = false;
389                                                 try {
390                                                         line = line.split("\\*\\/")[1]
391                                                                         .replace("*/", "");
392                                                 } catch (Exception e) {
393                                                         policyLogger.info("Just for Logging"+e);
394                                                         line = "";
395                                                 }
396                                         }
397                                         if (comment) {
398                                                 continue;
399                                         }
400                                         if (flag) {
401                                                 params.append(line);
402                                         }
403                                         if (line.contains("rule") && line.contains(".Params\"")) {
404                                                 params.append(line);
405                                                 flag = true;
406                                         }
407                                         if (line.contains("end") && flag) {
408                                                 break;
409                                         }
410                                 }
411                                 params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8));
412                                 params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
413                         .replace("insert(params);end", "")
414                         .replace("params.set", ""));
415                                 String[] components = params.toString().split("\\);");
416                                 if(components!= null && components.length > 0){
417                                         for (int i = 0; i < components.length; i++) {
418                                                 String value = null;
419                                                 components[i] = components[i]+")";
420                                                 String caption = components[i].substring(0,
421                                                                 components[i].indexOf('('));
422                                                 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
423                                                 if (components[i].contains("(\"")) {
424                                                         value = components[i]
425                                                                         .substring(components[i].indexOf("(\""),
426                                                                                         components[i].indexOf("\")"))
427                                                                         .replace("(\"", "").replace("\")", "");
428                                                 } else {
429                                                         value = components[i]
430                                                                         .substring(components[i].indexOf('('),
431                                                                                         components[i].indexOf(')'))
432                                                                         .replace("(", "").replace(")", "");
433                                                 }
434                                                 dynamicLayoutMap.put(caption, value);
435
436                                         }
437                                 }
438                         } catch (Exception e) {
439                                 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
440                         } 
441                 }
442                 
443         }
444
445         // set View Rule
446         @SuppressWarnings("unchecked")
447         @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
448         public void setViewRule(HttpServletRequest request, HttpServletResponse response){
449                 try {
450                         ObjectMapper mapper = new ObjectMapper();
451                         mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
452                         JsonNode root = mapper.readTree(request.getReader());
453                         PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
454                         policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
455                         if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){
456                                 policyData.setEditPolicy(true);
457                         }
458
459                         String body = "";
460
461                         body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
462                                         brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
463                         body = body + findRule((String) policyData.getRuleName()) + "\n";
464                         StringBuilder generatedRule = new StringBuilder();
465                         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();");
466
467                         if(policyData.getRuleData().size() > 0){ 
468                                 for(Object keyValue: policyData.getRuleData().keySet()){ 
469                                         String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1); 
470                                         if (string.equals(keyValue)) { 
471                                                 generatedRule.append("\n\t\tparams.set" 
472                                                                 + key + "(\"" 
473                                                                 + policyData.getRuleData().get(keyValue).toString() + "\");"); 
474                                         } else { 
475                                                 generatedRule.append("\n\t\tparams.set" 
476                                                                 + key + "(" 
477                                                                 + policyData.getRuleData().get(keyValue).toString() + ");"); 
478                                         } 
479                                 } 
480                         }
481                         generatedRule.append("\n\t\tinsert(params);\nend");
482                         policyLogger.info("New rule generated with :" + generatedRule.toString());
483                         body = body + generatedRule.toString();
484                         // Expand the body. 
485                         Map<String,String> copyMap=new HashMap<>();
486                         copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
487                         copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
488                         copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
489                         copyMap.put("policyVersion", "1");
490                         //Finding all the keys in the Map data-structure.
491                         Set<String> keySet= copyMap.keySet();
492                         Iterator<String> iterator = keySet.iterator(); 
493                         Pattern p;
494                         Matcher m;
495                         while(iterator.hasNext()) {
496                                 //Converting the first character of the key into a lower case. 
497                                 String input= iterator.next();
498                                 String output  = Character.toLowerCase(input.charAt(0)) +
499                                                 (input.length() > 1 ? input.substring(1) : "");
500                                 //Searching for a pattern in the String using the key. 
501                                 p=Pattern.compile("\\$\\{"+output+"\\}");   
502                                 m=p.matcher(body);
503                                 //Replacing the value with the inputs provided by the user in the editor. 
504                                 body=m.replaceAll(copyMap.get(input));
505                         }
506                         response.setCharacterEncoding("UTF-8");
507                         response.setContentType("application / json");
508                         request.setCharacterEncoding("UTF-8");
509
510                         PrintWriter out = response.getWriter();
511                         String responseString = mapper.writeValueAsString(body);
512                         JSONObject j = new JSONObject("{policyData: " + responseString + "}");
513                         out.write(j.toString());
514                 } catch (Exception e) {
515                         policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);
516                 }       
517         }
518 }