2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.policy.controller;
23 import java.io.BufferedReader;
25 import java.io.FileReader;
26 import java.io.PrintWriter;
27 import java.nio.file.Files;
28 import java.nio.file.Paths;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.LinkedHashMap;
34 import java.util.List;
37 import java.util.regex.Matcher;
38 import java.util.regex.Pattern;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.servlet.http.HttpServletResponse;
42 import javax.xml.bind.JAXBElement;
44 import org.json.JSONObject;
45 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
46 import org.openecomp.policy.common.logging.flexlogger.Logger;
47 import org.openecomp.policy.rest.adapter.PolicyRestAdapter;
48 import org.openecomp.policy.rest.dao.CommonClassDao;
49 import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
50 import org.openecomp.policy.rest.jpa.PolicyEntity;
51 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
52 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
53 import org.springframework.beans.factory.annotation.Autowired;
54 import org.springframework.stereotype.Controller;
55 import org.springframework.web.bind.annotation.RequestMapping;
56 import org.springframework.web.servlet.ModelAndView;
58 import com.fasterxml.jackson.databind.DeserializationFeature;
59 import com.fasterxml.jackson.databind.JsonNode;
60 import com.fasterxml.jackson.databind.ObjectMapper;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
72 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
76 public class CreateBRMSParamController extends RestrictedBaseController {
77 private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class);
79 private static CommonClassDao commonClassDao;
81 public static CommonClassDao getCommonClassDao() {
82 return commonClassDao;
85 public static void setCommonClassDao(CommonClassDao commonClassDao) {
86 CreateBRMSParamController.commonClassDao = commonClassDao;
90 private CreateBRMSParamController(CommonClassDao commonClassDao){
91 CreateBRMSParamController.commonClassDao = commonClassDao;
94 public CreateBRMSParamController(){}
95 protected PolicyRestAdapter policyAdapter = null;
97 private HashMap<String, String> dynamicLayoutMap;
99 private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
100 private static String string = "String";
103 @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
104 public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){
106 dynamicLayoutMap = new HashMap<>();
107 ObjectMapper mapper = new ObjectMapper();
108 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
109 JsonNode root = mapper.readTree(request.getReader());
110 String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", ""));
112 response.setCharacterEncoding(PolicyController.getCharacterencoding());
113 response.setContentType(PolicyController.getContenttype());
114 request.setCharacterEncoding(PolicyController.getCharacterencoding());
116 PrintWriter out = response.getWriter();
117 String responseString = mapper.writeValueAsString(dynamicLayoutMap);
118 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
119 out.write(j.toString());
121 policyLogger.error("Exception Occured while getting BRMS Rule data" , e);
125 protected String findRule(String ruleTemplate) {
126 List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate);
127 if(datas != null && !datas.isEmpty()){
128 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0);
129 return bRMSParamTemplate.getRule();
134 protected void generateUI(String rule) {
137 StringBuilder params = new StringBuilder("");
138 Boolean flag = false;
139 Boolean comment = false;
140 String lines[] = rule.split("\n");
141 for(String line : lines){
142 if (line.isEmpty() || line.startsWith("//")) {
145 if (line.startsWith("/*")) {
149 if (line.contains("//")) {
150 line = line.split("\\/\\/")[0];
152 if (line.contains("/*")) {
154 if (line.contains("*/")) {
157 line = line.split("\\/\\*")[0]
158 + line.split("\\*\\/")[1].replace("*/", "");
159 } catch (Exception e) {
160 policyLogger.info("Just for Logging"+e);
161 line = line.split("\\/\\*")[0];
164 line = line.split("\\/\\*")[0];
167 if (line.contains("*/")) {
170 line = line.split("\\*\\/")[1].replace("*/", "");
171 } catch (Exception e) {
172 policyLogger.info("Just for Logging"+e);
182 if (line.contains("declare Params")) {
186 if (line.contains("end") && flag) {
190 params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
191 String[] components = params.toString().split(":");
193 for (int i = 0; i < components.length; i++) {
196 caption = components[i];
198 if("".equals(caption)){
201 String nextComponent = "";
203 nextComponent = components[i + 1];
204 } catch (Exception e) {
205 policyLogger.info("Just for Logging"+e);
206 nextComponent = components[i];
208 if (nextComponent.startsWith(string)) {
210 createField(caption, type);
211 caption = nextComponent.replace(string, "");
212 } else if (nextComponent.startsWith("int")) {
214 createField(caption, type);
215 caption = nextComponent.replace("int", "");
218 } catch (Exception e) {
219 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
224 private void createField(String caption, String type) {
225 dynamicLayoutMap.put(caption, type);
229 * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter.
230 * Which is used to bind the data in GUI
232 public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
233 dynamicLayoutMap = new HashMap<>();
234 if (policyAdapter.getPolicyData() instanceof PolicyType) {
235 PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
236 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
237 // policy name value is the policy name without any prefix and
239 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
240 if (policyLogger.isDebugEnabled()) {
241 policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
243 policyAdapter.setPolicyName(policyNameValue);
244 String description = "";
246 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
248 policyLogger.info("Just for Logging"+e);
249 description = policy.getDescription();
251 policyAdapter.setPolicyDescription(description);
252 setDataAdapterFromAdviceExpressions(policy, policyAdapter);
253 paramUIGenerate(policyAdapter, entity);
254 // Get the target data under policy.
255 policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
256 if(policyAdapter.getDynamicLayoutMap().size() > 0){
257 LinkedHashMap<String,String> drlRule = new LinkedHashMap<>();
258 for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
259 drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue));
261 policyAdapter.setRuleData(drlRule);
263 TargetType target = policy.getTarget();
264 if (target != null) {
265 setDataToAdapterFromTarget(target, policyAdapter);
270 private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){
271 ArrayList<Object> attributeList = new ArrayList<>();
273 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
274 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
275 for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
276 if(attributeAssignment.getAttributeId().startsWith("key:")){
277 Map<String, String> attribute = new HashMap<>();
278 String key = attributeAssignment.getAttributeId().replace("key:", "");
279 attribute.put("key", key);
280 @SuppressWarnings("unchecked")
281 JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
282 String value = (String) attributevalue.getValue().getContent().get(0);
283 attribute.put("value", value);
284 attributeList.add(attribute);
285 }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
286 ArrayList<String> dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
287 if(dependencies.contains("")){
288 dependencies.remove("");
290 policyAdapter.setBrmsDependency(dependencies);
291 }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
292 policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
295 policyAdapter.setAttributes(attributeList);
299 private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){
300 // Under target we have AnyOFType
301 List<AnyOfType> anyOfList = target.getAnyOf();
302 if (anyOfList != null) {
303 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
304 while (iterAnyOf.hasNext()) {
305 AnyOfType anyOf = iterAnyOf.next();
306 // Under AnyOFType we have AllOFType
307 List<AllOfType> allOfList = anyOf.getAllOf();
308 if (allOfList != null) {
309 Iterator<AllOfType> iterAllOf = allOfList.iterator();
310 while (iterAllOf.hasNext()) {
311 AllOfType allOf = iterAllOf.next();
312 // Under AllOFType we have Match
313 List<MatchType> matchList = allOf.getMatch();
314 if (matchList != null) {
315 setDataToAdapterFromMatchList(matchList, policyAdapter);
323 private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){
324 Iterator<MatchType> iterMatch = matchList.iterator();
325 while (iterMatch.hasNext()) {
326 MatchType match = iterMatch.next();
328 // Under the match we have attribute value and
329 // attributeDesignator. So,finally down to the actual attribute.
331 AttributeValueType attributeValue = match.getAttributeValue();
332 String value = (String) attributeValue.getContent().get(0);
333 AttributeDesignatorType designator = match.getAttributeDesignator();
334 String attributeId = designator.getAttributeId();
336 if ("RiskType".equals(attributeId)){
337 policyAdapter.setRiskType(value);
339 if ("RiskLevel".equals(attributeId)){
340 policyAdapter.setRiskLevel(value);
342 if ("guard".equals(attributeId)){
343 policyAdapter.setGuard(value);
345 if ("TTLDate".equals(attributeId) && !value.contains("NA")){
346 String newDate = convertDate(value, true);
347 policyAdapter.setTtlDate(newDate);
352 private String convertDate(String dateTTL, boolean portalType) {
353 String formateDate = null;
358 parts = dateTTL.split("-");
359 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
361 date = dateTTL.split("T");
362 parts = date[0].split("-");
363 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
367 // This method generates the UI from rule configuration
368 public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
369 String data = entity.getConfigurationData().getConfigBody();
371 File file = new File(PolicyController.getConfigHome() +File.separator+ entity.getConfigurationData().getConfigurationName());
373 try (BufferedReader br = new BufferedReader(new FileReader(file))) {
374 StringBuilder sb = new StringBuilder();
375 String line = br.readLine();
376 while (line != null) {
379 line = br.readLine();
382 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage() + e);
386 StringBuilder params = new StringBuilder("");
387 Boolean flag = false;
388 Boolean comment = false;
389 for (String line : Files.readAllLines(Paths.get(file.toString()))) {
390 if (line.isEmpty() || line.startsWith("//")) {
393 if(line.contains(brmsTemplateVlaue)){
394 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
395 value = value.replace(brmsTemplateVlaue, "");
396 policyAdapter.setRuleName(value);
398 if (line.startsWith("/*")) {
402 if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){
403 line = line.split("\\/\\/")[0];
405 if (line.contains("/*")) {
407 if (line.contains("*/")) {
410 line = line.split("\\/\\*")[0]
411 + line.split("\\*\\/")[1].replace(
413 } catch (Exception e) {
414 policyLogger.info("Just for Logging"+e);
415 line = line.split("\\/\\*")[0];
418 line = line.split("\\/\\*")[0];
421 if (line.contains("*/")) {
424 line = line.split("\\*\\/")[1]
426 } catch (Exception e) {
427 policyLogger.info("Just for Logging"+e);
437 if (line.contains("rule") && line.contains(".Params\"")) {
441 if (line.contains("end") && flag) {
445 params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8));
446 params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
447 .replace("insert(params);end", "")
448 .replace("params.set", ""));
449 String[] components = params.toString().split("\\);");
450 if(components!= null && components.length > 0){
451 for (int i = 0; i < components.length; i++) {
453 components[i] = components[i]+")";
454 String caption = components[i].substring(0,
455 components[i].indexOf('('));
456 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
457 if (components[i].contains("(\"")) {
458 value = components[i]
459 .substring(components[i].indexOf("(\""),
460 components[i].indexOf("\")"))
461 .replace("(\"", "").replace("\")", "");
463 value = components[i]
464 .substring(components[i].indexOf('('),
465 components[i].indexOf(')'))
466 .replace("(", "").replace(")", "");
468 dynamicLayoutMap.put(caption, value);
472 } catch (Exception e) {
473 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
480 @SuppressWarnings("unchecked")
481 @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
482 public void setViewRule(HttpServletRequest request, HttpServletResponse response){
484 ObjectMapper mapper = new ObjectMapper();
485 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
486 JsonNode root = mapper.readTree(request.getReader());
487 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
488 policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
489 if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){
490 policyData.setEditPolicy(true);
495 body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
496 brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
497 body = body + findRule((String) policyData.getRuleName()) + "\n";
498 StringBuilder generatedRule = new StringBuilder();
499 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();");
501 if(policyData.getRuleData().size() > 0){
502 for(Object keyValue: policyData.getRuleData().keySet()){
503 String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
504 if (string.equals(keyValue)) {
505 generatedRule.append("\n\t\tparams.set"
507 + policyData.getRuleData().get(keyValue).toString() + "\");");
509 generatedRule.append("\n\t\tparams.set"
511 + policyData.getRuleData().get(keyValue).toString() + ");");
515 generatedRule.append("\n\t\tinsert(params);\nend");
516 policyLogger.info("New rule generated with :" + generatedRule.toString());
517 body = body + generatedRule.toString();
519 Map<String,String> copyMap=new HashMap<>();
520 copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
521 copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
522 copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
523 copyMap.put("policyVersion", "1");
524 //Finding all the keys in the Map data-structure.
525 Set<String> keySet= copyMap.keySet();
526 Iterator<String> iterator = keySet.iterator();
529 while(iterator.hasNext()) {
530 //Converting the first character of the key into a lower case.
531 String input= iterator.next();
532 String output = Character.toLowerCase(input.charAt(0)) +
533 (input.length() > 1 ? input.substring(1) : "");
534 //Searching for a pattern in the String using the key.
535 p=Pattern.compile("\\$\\{"+output+"\\}");
537 //Replacing the value with the inputs provided by the user in the editor.
538 body=m.replaceAll(copyMap.get(input));
540 response.setCharacterEncoding("UTF-8");
541 response.setContentType("application / json");
542 request.setCharacterEncoding("UTF-8");
544 PrintWriter out = response.getWriter();
545 String responseString = mapper.writeValueAsString(body);
546 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
547 out.write(j.toString());
548 } catch (Exception e) {
549 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);