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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger;
46 import org.onap.policy.common.logging.flexlogger.Logger;
47 import org.onap.policy.rest.adapter.PolicyRestAdapter;
48 import org.onap.policy.rest.dao.CommonClassDao;
49 import org.onap.policy.rest.jpa.BRMSParamTemplate;
50 import org.onap.policy.rest.jpa.PolicyEntity;
51 import org.onap.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;
57 import com.fasterxml.jackson.databind.DeserializationFeature;
58 import com.fasterxml.jackson.databind.JsonNode;
59 import com.fasterxml.jackson.databind.ObjectMapper;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
71 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
75 public class CreateBRMSParamController extends RestrictedBaseController {
76 private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class);
78 private static CommonClassDao commonClassDao;
80 public static CommonClassDao getCommonClassDao() {
81 return commonClassDao;
84 public static void setCommonClassDao(CommonClassDao commonClassDao) {
85 CreateBRMSParamController.commonClassDao = commonClassDao;
89 private CreateBRMSParamController(CommonClassDao commonClassDao){
90 CreateBRMSParamController.commonClassDao = commonClassDao;
93 public CreateBRMSParamController(){}
94 protected PolicyRestAdapter policyAdapter = null;
96 private HashMap<String, String> dynamicLayoutMap;
98 private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
99 private static String string = "String";
102 @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
103 public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){
105 dynamicLayoutMap = new HashMap<>();
106 ObjectMapper mapper = new ObjectMapper();
107 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
108 JsonNode root = mapper.readTree(request.getReader());
109 String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", ""));
111 response.setCharacterEncoding(PolicyController.getCharacterencoding());
112 response.setContentType(PolicyController.getContenttype());
113 request.setCharacterEncoding(PolicyController.getCharacterencoding());
115 PrintWriter out = response.getWriter();
116 String responseString = mapper.writeValueAsString(dynamicLayoutMap);
117 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
118 out.write(j.toString());
120 policyLogger.error("Exception Occured while getting BRMS Rule data" , e);
124 protected String findRule(String ruleTemplate) {
125 List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate);
126 if(datas != null && !datas.isEmpty()){
127 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0);
128 return bRMSParamTemplate.getRule();
133 protected void generateUI(String rule) {
136 StringBuilder params = new StringBuilder("");
137 Boolean flag = false;
138 Boolean comment = false;
139 String lines[] = rule.split("\n");
140 for(String line : lines){
141 if (line.isEmpty() || line.startsWith("//")) {
144 if (line.startsWith("/*")) {
148 if (line.contains("//")) {
149 line = line.split("\\/\\/")[0];
151 if (line.contains("/*")) {
153 if (line.contains("*/")) {
156 line = line.split("\\/\\*")[0]
157 + line.split("\\*\\/")[1].replace("*/", "");
158 } catch (Exception e) {
159 policyLogger.info("Just for Logging"+e);
160 line = line.split("\\/\\*")[0];
163 line = line.split("\\/\\*")[0];
166 if (line.contains("*/")) {
169 line = line.split("\\*\\/")[1].replace("*/", "");
170 } catch (Exception e) {
171 policyLogger.info("Just for Logging"+e);
181 if (line.contains("declare Params")) {
185 if (line.contains("end") && flag) {
189 params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
190 String[] components = params.toString().split(":");
192 for (int i = 0; i < components.length; i++) {
195 caption = components[i];
197 if("".equals(caption)){
200 String nextComponent = "";
202 nextComponent = components[i + 1];
203 } catch (Exception e) {
204 policyLogger.info("Just for Logging"+e);
205 nextComponent = components[i];
207 if (nextComponent.startsWith(string)) {
209 createField(caption, type);
210 caption = nextComponent.replace(string, "");
211 } else if (nextComponent.startsWith("int")) {
213 createField(caption, type);
214 caption = nextComponent.replace("int", "");
217 } catch (Exception e) {
218 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
223 private void createField(String caption, String type) {
224 dynamicLayoutMap.put(caption, type);
228 * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter.
229 * Which is used to bind the data in GUI
231 public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
232 dynamicLayoutMap = new HashMap<>();
233 if (policyAdapter.getPolicyData() instanceof PolicyType) {
234 PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
235 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
236 // policy name value is the policy name without any prefix and
238 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
239 if (policyLogger.isDebugEnabled()) {
240 policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
242 policyAdapter.setPolicyName(policyNameValue);
243 String description = "";
245 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
247 policyLogger.info("Just for Logging"+e);
248 description = policy.getDescription();
250 policyAdapter.setPolicyDescription(description);
251 setDataAdapterFromAdviceExpressions(policy, policyAdapter);
252 paramUIGenerate(policyAdapter, entity);
253 // Get the target data under policy.
254 policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
255 if(policyAdapter.getDynamicLayoutMap().size() > 0){
256 LinkedHashMap<String,String> drlRule = new LinkedHashMap<>();
257 for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
258 drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue));
260 policyAdapter.setRuleData(drlRule);
262 TargetType target = policy.getTarget();
263 if (target != null) {
264 setDataToAdapterFromTarget(target, policyAdapter);
269 private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){
270 ArrayList<Object> attributeList = new ArrayList<>();
272 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
273 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
274 for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
275 if(attributeAssignment.getAttributeId().startsWith("key:")){
276 Map<String, String> attribute = new HashMap<>();
277 String key = attributeAssignment.getAttributeId().replace("key:", "");
278 attribute.put("key", key);
279 @SuppressWarnings("unchecked")
280 JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
281 String value = (String) attributevalue.getValue().getContent().get(0);
282 attribute.put("value", value);
283 attributeList.add(attribute);
284 }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
285 ArrayList<String> dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
286 if(dependencies.contains("")){
287 dependencies.remove("");
289 policyAdapter.setBrmsDependency(dependencies);
290 }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
291 policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
294 policyAdapter.setAttributes(attributeList);
298 private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){
299 // Under target we have AnyOFType
300 List<AnyOfType> anyOfList = target.getAnyOf();
301 if (anyOfList != null) {
302 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
303 while (iterAnyOf.hasNext()) {
304 AnyOfType anyOf = iterAnyOf.next();
305 // Under AnyOFType we have AllOFType
306 List<AllOfType> allOfList = anyOf.getAllOf();
307 if (allOfList != null) {
308 Iterator<AllOfType> iterAllOf = allOfList.iterator();
309 while (iterAllOf.hasNext()) {
310 AllOfType allOf = iterAllOf.next();
311 // Under AllOFType we have Match
312 List<MatchType> matchList = allOf.getMatch();
313 if (matchList != null) {
314 setDataToAdapterFromMatchList(matchList, policyAdapter);
322 private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){
323 Iterator<MatchType> iterMatch = matchList.iterator();
324 while (iterMatch.hasNext()) {
325 MatchType match = iterMatch.next();
327 // Under the match we have attribute value and
328 // attributeDesignator. So,finally down to the actual attribute.
330 AttributeValueType attributeValue = match.getAttributeValue();
331 String value = (String) attributeValue.getContent().get(0);
332 AttributeDesignatorType designator = match.getAttributeDesignator();
333 String attributeId = designator.getAttributeId();
335 if ("RiskType".equals(attributeId)){
336 policyAdapter.setRiskType(value);
338 if ("RiskLevel".equals(attributeId)){
339 policyAdapter.setRiskLevel(value);
341 if ("guard".equals(attributeId)){
342 policyAdapter.setGuard(value);
344 if ("TTLDate".equals(attributeId) && !value.contains("NA")){
345 String newDate = convertDate(value, true);
346 policyAdapter.setTtlDate(newDate);
351 private String convertDate(String dateTTL, boolean portalType) {
352 String formateDate = null;
357 parts = dateTTL.split("-");
358 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
360 date = dateTTL.split("T");
361 parts = date[0].split("-");
362 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
366 // This method generates the UI from rule configuration
367 public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
368 String data = entity.getConfigurationData().getConfigBody();
370 File file = new File(PolicyController.getConfigHome() +File.separator+ entity.getConfigurationData().getConfigurationName());
372 try (BufferedReader br = new BufferedReader(new FileReader(file))) {
373 StringBuilder sb = new StringBuilder();
374 String line = br.readLine();
375 while (line != null) {
378 line = br.readLine();
381 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage() + e);
385 StringBuilder params = new StringBuilder("");
386 Boolean flag = false;
387 Boolean comment = false;
388 for (String line : Files.readAllLines(Paths.get(file.toString()))) {
389 if (line.isEmpty() || line.startsWith("//")) {
392 if(line.contains(brmsTemplateVlaue)){
393 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
394 value = value.replace(brmsTemplateVlaue, "");
395 policyAdapter.setRuleName(value);
397 if (line.startsWith("/*")) {
401 if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){
402 line = line.split("\\/\\/")[0];
404 if (line.contains("/*")) {
406 if (line.contains("*/")) {
409 line = line.split("\\/\\*")[0]
410 + line.split("\\*\\/")[1].replace(
412 } catch (Exception e) {
413 policyLogger.info("Just for Logging"+e);
414 line = line.split("\\/\\*")[0];
417 line = line.split("\\/\\*")[0];
420 if (line.contains("*/")) {
423 line = line.split("\\*\\/")[1]
425 } catch (Exception e) {
426 policyLogger.info("Just for Logging"+e);
436 if (line.contains("rule") && line.contains(".Params\"")) {
440 if (line.contains("end") && flag) {
444 params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8));
445 params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
446 .replace("insert(params);end", "")
447 .replace("params.set", ""));
448 String[] components = params.toString().split("\\);");
449 if(components!= null && components.length > 0){
450 for (int i = 0; i < components.length; i++) {
452 components[i] = components[i]+")";
453 String caption = components[i].substring(0,
454 components[i].indexOf('('));
455 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
456 if (components[i].contains("(\"")) {
457 value = components[i]
458 .substring(components[i].indexOf("(\""),
459 components[i].indexOf("\")"))
460 .replace("(\"", "").replace("\")", "");
462 value = components[i]
463 .substring(components[i].indexOf('('),
464 components[i].indexOf(')'))
465 .replace("(", "").replace(")", "");
467 dynamicLayoutMap.put(caption, value);
471 } catch (Exception e) {
472 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
479 @SuppressWarnings("unchecked")
480 @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
481 public void setViewRule(HttpServletRequest request, HttpServletResponse response){
483 ObjectMapper mapper = new ObjectMapper();
484 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
485 JsonNode root = mapper.readTree(request.getReader());
486 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
487 policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
488 if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){
489 policyData.setEditPolicy(true);
494 body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
495 brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
496 body = body + findRule((String) policyData.getRuleName()) + "\n";
497 StringBuilder generatedRule = new StringBuilder();
498 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();");
500 if(policyData.getRuleData().size() > 0){
501 for(Object keyValue: policyData.getRuleData().keySet()){
502 String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
503 if (string.equals(keyValue)) {
504 generatedRule.append("\n\t\tparams.set"
506 + policyData.getRuleData().get(keyValue).toString() + "\");");
508 generatedRule.append("\n\t\tparams.set"
510 + policyData.getRuleData().get(keyValue).toString() + ");");
514 generatedRule.append("\n\t\tinsert(params);\nend");
515 policyLogger.info("New rule generated with :" + generatedRule.toString());
516 body = body + generatedRule.toString();
518 Map<String,String> copyMap=new HashMap<>();
519 copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
520 copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
521 copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
522 copyMap.put("policyVersion", "1");
523 //Finding all the keys in the Map data-structure.
524 Set<String> keySet= copyMap.keySet();
525 Iterator<String> iterator = keySet.iterator();
528 while(iterator.hasNext()) {
529 //Converting the first character of the key into a lower case.
530 String input= iterator.next();
531 String output = Character.toLowerCase(input.charAt(0)) +
532 (input.length() > 1 ? input.substring(1) : "");
533 //Searching for a pattern in the String using the key.
534 p=Pattern.compile("\\$\\{"+output+"\\}");
536 //Replacing the value with the inputs provided by the user in the editor.
537 body=m.replaceAll(copyMap.get(input));
539 response.setCharacterEncoding("UTF-8");
540 response.setContentType("application / json");
541 request.setCharacterEncoding("UTF-8");
543 PrintWriter out = response.getWriter();
544 String responseString = mapper.writeValueAsString(body);
545 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
546 out.write(j.toString());
547 } catch (Exception e) {
548 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);