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