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