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