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.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;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
35 import javax.servlet.http.HttpServletRequest;
36 import javax.servlet.http.HttpServletResponse;
37 import javax.xml.bind.JAXBElement;
39 import org.json.JSONObject;
40 import org.onap.policy.common.logging.flexlogger.FlexLogger;
41 import org.onap.policy.common.logging.flexlogger.Logger;
42 import org.onap.policy.rest.adapter.PolicyRestAdapter;
43 import org.onap.policy.rest.dao.CommonClassDao;
44 import org.onap.policy.rest.jpa.BRMSParamTemplate;
45 import org.onap.policy.rest.jpa.PolicyEntity;
46 import org.onap.policy.xacml.api.XACMLErrorConstants;
47 import org.onap.portalsdk.core.controller.RestrictedBaseController;
48 import org.springframework.beans.factory.annotation.Autowired;
49 import org.springframework.stereotype.Controller;
50 import org.springframework.web.bind.annotation.RequestMapping;
52 import com.fasterxml.jackson.databind.DeserializationFeature;
53 import com.fasterxml.jackson.databind.JsonNode;
54 import com.fasterxml.jackson.databind.ObjectMapper;
56 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
57 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
58 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
59 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
70 public class CreateBRMSParamController extends RestrictedBaseController {
71 private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class);
73 private static CommonClassDao commonClassDao;
75 public static CommonClassDao getCommonClassDao() {
76 return commonClassDao;
79 public static void setCommonClassDao(CommonClassDao commonClassDao) {
80 CreateBRMSParamController.commonClassDao = commonClassDao;
84 private CreateBRMSParamController(CommonClassDao commonClassDao){
85 CreateBRMSParamController.commonClassDao = commonClassDao;
88 public CreateBRMSParamController(){}
89 protected PolicyRestAdapter policyAdapter = null;
91 private HashMap<String, String> dynamicLayoutMap;
93 private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
94 private static String string = "String";
97 @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
98 public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){
100 dynamicLayoutMap = new HashMap<>();
101 ObjectMapper mapper = new ObjectMapper();
102 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
103 JsonNode root = mapper.readTree(request.getReader());
104 String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", ""));
106 response.setCharacterEncoding(PolicyController.getCharacterencoding());
107 response.setContentType(PolicyController.getContenttype());
108 request.setCharacterEncoding(PolicyController.getCharacterencoding());
110 PrintWriter out = response.getWriter();
111 String responseString = mapper.writeValueAsString(dynamicLayoutMap);
112 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
113 out.write(j.toString());
115 policyLogger.error("Exception Occured while getting BRMS Rule data" , e);
119 protected String findRule(String ruleTemplate) {
120 List<Object> datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate);
121 if(datas != null && !datas.isEmpty()){
122 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0);
123 return bRMSParamTemplate.getRule();
128 protected void generateUI(String rule) {
131 StringBuilder params = new StringBuilder("");
132 Boolean flag = false;
133 Boolean comment = false;
134 String lines[] = rule.split("\n");
135 for(String line : lines){
136 if (line.isEmpty() || line.startsWith("//")) {
139 if (line.startsWith("/*")) {
143 if (line.contains("//")) {
144 line = line.split("\\/\\/")[0];
146 if (line.contains("/*")) {
148 if (line.contains("*/")) {
151 line = line.split("\\/\\*")[0]
152 + line.split("\\*\\/")[1].replace("*/", "");
153 } catch (Exception e) {
154 policyLogger.info("Just for Logging"+e);
155 line = line.split("\\/\\*")[0];
158 line = line.split("\\/\\*")[0];
161 if (line.contains("*/")) {
164 line = line.split("\\*\\/")[1].replace("*/", "");
165 } catch (Exception e) {
166 policyLogger.info("Just for Logging"+e);
176 if (line.contains("declare PapParams")) {
180 if (line.contains("end") && flag) {
184 params = new StringBuilder(params.toString().replace("declare PapParams", "").replace("end", "").replaceAll("\\s+", ""));
185 String[] components = params.toString().split(":");
187 for (int i = 0; i < components.length; i++) {
190 caption = components[i];
192 if("".equals(caption)){
195 String nextComponent = "";
197 nextComponent = components[i + 1];
198 } catch (Exception e) {
199 policyLogger.info("Just for Logging"+e);
200 nextComponent = components[i];
202 if (nextComponent.startsWith(string)) {
204 createField(caption, type);
205 caption = nextComponent.replace(string, "");
206 } else if (nextComponent.startsWith("int")) {
208 createField(caption, type);
209 caption = nextComponent.replace("int", "");
212 } catch (Exception e) {
213 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
218 private void createField(String caption, String type) {
219 dynamicLayoutMap.put(caption, type);
223 * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter.
224 * Which is used to bind the data in GUI
226 public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
227 dynamicLayoutMap = new HashMap<>();
228 if (policyAdapter.getPolicyData() instanceof PolicyType) {
229 PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
230 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
231 // policy name value is the policy name without any prefix and
233 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
234 if (policyLogger.isDebugEnabled()) {
235 policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
237 policyAdapter.setPolicyName(policyNameValue);
238 String description = "";
240 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
242 policyLogger.info("Just for Logging"+e);
243 description = policy.getDescription();
245 policyAdapter.setPolicyDescription(description);
246 setDataAdapterFromAdviceExpressions(policy, policyAdapter);
247 paramUIGenerate(policyAdapter, entity);
248 // Get the target data under policy.
249 policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
250 if(policyAdapter.getDynamicLayoutMap().size() > 0){
251 LinkedHashMap<String,String> drlRule = new LinkedHashMap<>();
252 for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
253 drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue));
255 policyAdapter.setRuleData(drlRule);
257 TargetType target = policy.getTarget();
258 if (target != null) {
259 setDataToAdapterFromTarget(target, policyAdapter);
264 private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){
265 ArrayList<Object> attributeList = new ArrayList<>();
267 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
268 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
269 for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
270 if(attributeAssignment.getAttributeId().startsWith("key:")){
271 Map<String, String> attribute = new HashMap<>();
272 String key = attributeAssignment.getAttributeId().replace("key:", "");
273 attribute.put("key", key);
274 @SuppressWarnings("unchecked")
275 JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
276 String value = (String) attributevalue.getValue().getContent().get(0);
277 attribute.put("value", value);
278 attributeList.add(attribute);
279 }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
280 ArrayList<String> dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
281 if(dependencies.contains("")){
282 dependencies.remove("");
284 policyAdapter.setBrmsDependency(dependencies);
285 }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
286 policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
289 policyAdapter.setAttributes(attributeList);
293 private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){
294 // Under target we have AnyOFType
295 List<AnyOfType> anyOfList = target.getAnyOf();
296 if (anyOfList != null) {
297 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
298 while (iterAnyOf.hasNext()) {
299 AnyOfType anyOf = iterAnyOf.next();
300 // Under AnyOFType we have AllOFType
301 List<AllOfType> allOfList = anyOf.getAllOf();
302 if (allOfList != null) {
303 Iterator<AllOfType> iterAllOf = allOfList.iterator();
304 while (iterAllOf.hasNext()) {
305 AllOfType allOf = iterAllOf.next();
306 // Under AllOFType we have Match
307 List<MatchType> matchList = allOf.getMatch();
308 if (matchList != null) {
309 setDataToAdapterFromMatchList(matchList, policyAdapter);
317 private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){
318 Iterator<MatchType> iterMatch = matchList.iterator();
319 while (iterMatch.hasNext()) {
320 MatchType match = iterMatch.next();
322 // Under the match we have attribute value and
323 // attributeDesignator. So,finally down to the actual attribute.
325 AttributeValueType attributeValue = match.getAttributeValue();
326 String value = (String) attributeValue.getContent().get(0);
327 AttributeDesignatorType designator = match.getAttributeDesignator();
328 String attributeId = designator.getAttributeId();
330 if ("RiskType".equals(attributeId)){
331 policyAdapter.setRiskType(value);
333 if ("RiskLevel".equals(attributeId)){
334 policyAdapter.setRiskLevel(value);
336 if ("guard".equals(attributeId)){
337 policyAdapter.setGuard(value);
339 if ("TTLDate".equals(attributeId) && !value.contains("NA")){
340 PolicyController controller = new PolicyController();
341 String newDate = controller.convertDate(value);
342 policyAdapter.setTtlDate(newDate);
347 // This method generates the UI from rule configuration
348 public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
349 String data = entity.getConfigurationData().getConfigBody();
352 StringBuilder params = new StringBuilder("");
353 Boolean flag = false;
354 Boolean comment = false;
355 for (String line : data.split("\n")) {
356 if (line.isEmpty() || line.startsWith("//")) {
359 if(line.contains(brmsTemplateVlaue)){
360 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
361 value = value.replace(brmsTemplateVlaue, "");
362 policyAdapter.setRuleName(value);
364 if (line.startsWith("/*")) {
368 if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){
369 line = line.split("\\/\\/")[0];
371 if (line.contains("/*")) {
373 if (line.contains("*/")) {
376 line = line.split("\\/\\*")[0]
377 + line.split("\\*\\/")[1].replace(
379 } catch (Exception e) {
380 policyLogger.info("Just for Logging"+e);
381 line = line.split("\\/\\*")[0];
384 line = line.split("\\/\\*")[0];
387 if (line.contains("*/")) {
390 line = line.split("\\*\\/")[1]
392 } catch (Exception e) {
393 policyLogger.info("Just for Logging"+e);
403 if (line.contains("rule") && line.contains(".PapParams\"")) {
407 if (line.contains("end") && flag) {
411 params = new StringBuilder(params.substring(params.indexOf(".PapParams\"")+ 11));
412 params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenPapParamsparams=newPapParams();","")
413 .replace("insert(params);end", "")
414 .replace("params.set", ""));
415 String[] components = params.toString().split("\\);");
416 if(components!= null && components.length > 0){
417 for (int i = 0; i < components.length; i++) {
419 components[i] = components[i]+")";
420 String caption = components[i].substring(0,
421 components[i].indexOf('('));
422 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
423 if (components[i].contains("(\"")) {
424 value = components[i]
425 .substring(components[i].indexOf("(\""),
426 components[i].indexOf("\")"))
427 .replace("(\"", "").replace("\")", "");
429 value = components[i]
430 .substring(components[i].indexOf('('),
431 components[i].indexOf(')'))
432 .replace("(", "").replace(")", "");
434 dynamicLayoutMap.put(caption, value);
438 } catch (Exception e) {
439 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
446 @SuppressWarnings("unchecked")
447 @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
448 public void setViewRule(HttpServletRequest request, HttpServletResponse response){
450 ObjectMapper mapper = new ObjectMapper();
451 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
452 JsonNode root = mapper.readTree(request.getReader());
453 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
454 policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
455 if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){
456 policyData.setEditPolicy(true);
461 body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
462 brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
463 body = body + findRule((String) policyData.getRuleName()) + "\n";
464 StringBuilder generatedRule = new StringBuilder();
465 generatedRule.append("rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".PapParams\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tPapParams params = new PapParams();");
467 if(policyData.getRuleData().size() > 0){
468 for(Object keyValue: policyData.getRuleData().keySet()){
469 String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
470 if (string.equals(keyValue)) {
471 generatedRule.append("\n\t\tparams.set"
473 + policyData.getRuleData().get(keyValue).toString() + "\");");
475 generatedRule.append("\n\t\tparams.set"
477 + policyData.getRuleData().get(keyValue).toString() + ");");
481 generatedRule.append("\n\t\tinsert(params);\nend");
482 policyLogger.info("New rule generated with :" + generatedRule.toString());
483 body = body + generatedRule.toString();
485 Map<String,String> copyMap=new HashMap<>();
486 copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
487 copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
488 copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
489 copyMap.put("policyVersion", "1");
490 //Finding all the keys in the Map data-structure.
491 Set<String> keySet= copyMap.keySet();
492 Iterator<String> iterator = keySet.iterator();
495 while(iterator.hasNext()) {
496 //Converting the first character of the key into a lower case.
497 String input= iterator.next();
498 String output = Character.toLowerCase(input.charAt(0)) +
499 (input.length() > 1 ? input.substring(1) : "");
500 //Searching for a pattern in the String using the key.
501 p=Pattern.compile("\\$\\{"+output+"\\}");
503 //Replacing the value with the inputs provided by the user in the editor.
504 body=m.replaceAll(copyMap.get(input));
506 response.setCharacterEncoding("UTF-8");
507 response.setContentType("application / json");
508 request.setCharacterEncoding("UTF-8");
510 PrintWriter out = response.getWriter();
511 String responseString = mapper.writeValueAsString(body);
512 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
513 out.write(j.toString());
514 } catch (Exception e) {
515 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);