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.rest.adapter.PolicyRestAdapter;
46 import org.openecomp.policy.rest.dao.CommonClassDao;
47 import org.openecomp.policy.rest.jpa.BRMSParamTemplate;
48 import org.openecomp.policy.rest.jpa.PolicyEntity;
49 import org.openecomp.portalsdk.core.controller.RestrictedBaseController;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.stereotype.Controller;
52 import org.springframework.web.bind.annotation.RequestMapping;
53 import org.springframework.web.servlet.ModelAndView;
55 import org.openecomp.policy.xacml.api.XACMLErrorConstants;
56 import com.fasterxml.jackson.databind.DeserializationFeature;
57 import com.fasterxml.jackson.databind.JsonNode;
58 import com.fasterxml.jackson.databind.ObjectMapper;
60 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType;
65 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType;
66 import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType;
67 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
68 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
69 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
70 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
72 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
73 import org.openecomp.policy.common.logging.flexlogger.Logger;
77 public class CreateBRMSParamController extends RestrictedBaseController {
78 private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class);
80 private static CommonClassDao commonClassDao;
83 private CreateBRMSParamController(CommonClassDao commonClassDao){
84 CreateBRMSParamController.commonClassDao = commonClassDao;
87 public CreateBRMSParamController(){}
88 protected PolicyRestAdapter policyAdapter = null;
90 private HashMap<String, String> dynamicLayoutMap;
92 private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
93 private static String String = "String";
96 @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
97 public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{
98 dynamicLayoutMap = new HashMap<>();
99 ObjectMapper mapper = new ObjectMapper();
100 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
101 JsonNode root = mapper.readTree(request.getReader());
102 String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", ""));
104 response.setCharacterEncoding(PolicyController.getCharacterencoding());
105 response.setContentType(PolicyController.getContenttype());
106 request.setCharacterEncoding(PolicyController.getCharacterencoding());
108 PrintWriter out = response.getWriter();
109 String responseString = mapper.writeValueAsString(dynamicLayoutMap);
110 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
111 out.write(j.toString());
115 protected String findRule(String ruleTemplate) {
116 List<Object> datas = commonClassDao.getData(BRMSParamTemplate.class);
117 for (Object data: datas){
118 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) data;
119 if(bRMSParamTemplate.getRuleName().equals(ruleTemplate)){
120 return bRMSParamTemplate.getRule();
126 protected void generateUI(String rule) {
129 StringBuilder params = new StringBuilder("");
130 Boolean flag = false;
131 Boolean comment = false;
132 String lines[] = rule.split("\n");
133 for(String line : lines){
134 if (line.isEmpty() || line.startsWith("//")) {
137 if (line.startsWith("/*")) {
141 if (line.contains("//")) {
142 line = line.split("\\/\\/")[0];
144 if (line.contains("/*")) {
146 if (line.contains("*/")) {
149 line = line.split("\\/\\*")[0]
150 + line.split("\\*\\/")[1].replace("*/", "");
151 } catch (Exception e) {
152 policyLogger.info("Just for Logging"+e);
153 line = line.split("\\/\\*")[0];
156 line = line.split("\\/\\*")[0];
159 if (line.contains("*/")) {
162 line = line.split("\\*\\/")[1].replace("*/", "");
163 } catch (Exception e) {
164 policyLogger.info("Just for Logging"+e);
174 if (line.contains("declare Params")) {
178 if (line.contains("end") && flag) {
182 params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
183 String[] components = params.toString().split(":");
185 for (int i = 0; i < components.length; i++) {
188 caption = components[i];
190 if("".equals(caption)){
193 String nextComponent = "";
195 nextComponent = components[i + 1];
196 } catch (Exception e) {
197 policyLogger.info("Just for Logging"+e);
198 nextComponent = components[i];
200 if (nextComponent.startsWith(String)) {
202 createField(caption, type);
203 caption = nextComponent.replace(String, "");
204 } else if (nextComponent.startsWith("int")) {
206 createField(caption, type);
207 caption = nextComponent.replace("int", "");
210 } catch (Exception e) {
211 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
216 private void createField(String caption, String type) {
217 dynamicLayoutMap.put(caption, type);
221 * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter.
222 * Which is used to bind the data in GUI
224 public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
225 dynamicLayoutMap = new HashMap<>();
226 if (policyAdapter.getPolicyData() instanceof PolicyType) {
227 PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
228 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
229 // policy name value is the policy name without any prefix and
231 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
232 if (policyLogger.isDebugEnabled()) {
233 policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
235 policyAdapter.setPolicyName(policyNameValue);
236 String description = "";
238 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
240 policyLogger.info("Just for Logging"+e);
241 description = policy.getDescription();
243 policyAdapter.setPolicyDescription(description);
244 setDataAdapterFromAdviceExpressions(policy, policyAdapter);
245 paramUIGenerate(policyAdapter, entity);
246 // Get the target data under policy.
247 policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
248 if(policyAdapter.getDynamicLayoutMap().size() > 0){
249 LinkedHashMap<String,String> drlRule = new LinkedHashMap<>();
250 for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
251 drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue));
253 policyAdapter.setRuleData(drlRule);
255 TargetType target = policy.getTarget();
256 if (target != null) {
257 setDataToAdapterFromTarget(target, policyAdapter);
262 private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){
263 ArrayList<Object> attributeList = new ArrayList<>();
265 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
266 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
267 for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
268 if(attributeAssignment.getAttributeId().startsWith("key:")){
269 Map<String, String> attribute = new HashMap<>();
270 String key = attributeAssignment.getAttributeId().replace("key:", "");
271 attribute.put("key", key);
272 @SuppressWarnings("unchecked")
273 JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
274 String value = (String) attributevalue.getValue().getContent().get(0);
275 attribute.put("value", value);
276 attributeList.add(attribute);
277 }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
278 ArrayList<String> dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
279 if(dependencies.contains("")){
280 dependencies.remove("");
282 policyAdapter.setBrmsDependency(dependencies);
283 }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
284 policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
287 policyAdapter.setAttributes(attributeList);
291 private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){
292 // Under target we have AnyOFType
293 List<AnyOfType> anyOfList = target.getAnyOf();
294 if (anyOfList != null) {
295 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
296 while (iterAnyOf.hasNext()) {
297 AnyOfType anyOf = iterAnyOf.next();
298 // Under AnyOFType we have AllOFType
299 List<AllOfType> allOfList = anyOf.getAllOf();
300 if (allOfList != null) {
301 Iterator<AllOfType> iterAllOf = allOfList.iterator();
302 while (iterAllOf.hasNext()) {
303 AllOfType allOf = iterAllOf.next();
304 // Under AllOFType we have Match
305 List<MatchType> matchList = allOf.getMatch();
306 if (matchList != null) {
307 setDataToAdapterFromMatchList(matchList, policyAdapter);
315 private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){
316 Iterator<MatchType> iterMatch = matchList.iterator();
317 while (iterMatch.hasNext()) {
318 MatchType match = iterMatch.next();
320 // Under the match we have attribute value and
321 // attributeDesignator. So,finally down to the actual attribute.
323 AttributeValueType attributeValue = match.getAttributeValue();
324 String value = (String) attributeValue.getContent().get(0);
325 AttributeDesignatorType designator = match.getAttributeDesignator();
326 String attributeId = designator.getAttributeId();
328 if ("RiskType".equals(attributeId)){
329 policyAdapter.setRiskType(value);
331 if ("RiskLevel".equals(attributeId)){
332 policyAdapter.setRiskLevel(value);
334 if ("guard".equals(attributeId)){
335 policyAdapter.setGuard(value);
337 if ("TTLDate".equals(attributeId) && !value.contains("NA")){
338 String newDate = convertDate(value, true);
339 policyAdapter.setTtlDate(newDate);
344 private String convertDate(String dateTTL, boolean portalType) {
345 String formateDate = null;
350 parts = dateTTL.split("-");
351 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
353 date = dateTTL.split("T");
354 parts = date[0].split("-");
355 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
359 // This method generates the UI from rule configuration
360 private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
361 String data = entity.getConfigurationData().getConfigBody();
363 File file = new File(PolicyController.getConfigHome() +File.separator+ entity.getConfigurationData().getConfigurationName());
365 try (BufferedReader br = new BufferedReader(new FileReader(file))) {
366 StringBuilder sb = new StringBuilder();
367 String line = br.readLine();
368 while (line != null) {
371 line = br.readLine();
374 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage() + e);
378 StringBuilder params = new StringBuilder("");
379 Boolean flag = false;
380 Boolean comment = false;
381 for (String line : Files.readAllLines(Paths.get(file.toString()))) {
382 if (line.isEmpty() || line.startsWith("//")) {
385 if(line.contains(brmsTemplateVlaue)){
386 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
387 value = value.replace(brmsTemplateVlaue, "");
388 policyAdapter.setRuleName(value);
390 if (line.startsWith("/*")) {
394 if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){
395 line = line.split("\\/\\/")[0];
397 if (line.contains("/*")) {
399 if (line.contains("*/")) {
402 line = line.split("\\/\\*")[0]
403 + line.split("\\*\\/")[1].replace(
405 } catch (Exception e) {
406 policyLogger.info("Just for Logging"+e);
407 line = line.split("\\/\\*")[0];
410 line = line.split("\\/\\*")[0];
413 if (line.contains("*/")) {
416 line = line.split("\\*\\/")[1]
418 } catch (Exception e) {
419 policyLogger.info("Just for Logging"+e);
429 if (line.contains("rule") && line.contains(".Params\"")) {
433 if (line.contains("end") && flag) {
437 params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8));
438 params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
439 .replace("insert(params);end", "")
440 .replace("params.set", ""));
441 String[] components = params.toString().split("\\);");
442 if(components!= null && components.length > 0){
443 for (int i = 0; i < components.length; i++) {
445 components[i] = components[i]+")";
446 String caption = components[i].substring(0,
447 components[i].indexOf('('));
448 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
449 if (components[i].contains("(\"")) {
450 value = components[i]
451 .substring(components[i].indexOf("(\""),
452 components[i].indexOf("\")"))
453 .replace("(\"", "").replace("\")", "");
455 value = components[i]
456 .substring(components[i].indexOf('('),
457 components[i].indexOf(')'))
458 .replace("(", "").replace(")", "");
460 dynamicLayoutMap.put(caption, value);
464 } catch (Exception e) {
465 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
472 @SuppressWarnings("unchecked")
473 @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
474 public ModelAndView setViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{
476 ObjectMapper mapper = new ObjectMapper();
477 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
478 JsonNode root = mapper.readTree(request.getReader());
479 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
480 policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
481 if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){
482 policyData.setEditPolicy(true);
487 body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
488 brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
489 body = body + findRule((String) policyData.getRuleName()) + "\n";
490 StringBuilder generatedRule = new StringBuilder();
491 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();");
493 if(policyData.getRuleData().size() > 0){
494 for(Object keyValue: policyData.getRuleData().keySet()){
495 String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
496 if (String.equals(keyValue)) {
497 generatedRule.append("\n\t\tparams.set"
499 + policyData.getRuleData().get(keyValue).toString() + "\");");
501 generatedRule.append("\n\t\tparams.set"
503 + policyData.getRuleData().get(keyValue).toString() + ");");
507 generatedRule.append("\n\t\tinsert(params);\nend");
508 policyLogger.info("New rule generated with :" + generatedRule.toString());
509 body = body + generatedRule.toString();
511 Map<String,String> copyMap=new HashMap<>();
512 copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
513 copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
514 copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
515 copyMap.put("policyVersion", "1");
516 //Finding all the keys in the Map data-structure.
517 Set<String> keySet= copyMap.keySet();
518 Iterator<String> iterator = keySet.iterator();
521 while(iterator.hasNext()) {
522 //Converting the first character of the key into a lower case.
523 String input= iterator.next();
524 String output = Character.toLowerCase(input.charAt(0)) +
525 (input.length() > 1 ? input.substring(1) : "");
526 //Searching for a pattern in the String using the key.
527 p=Pattern.compile("\\$\\{"+output+"\\}");
529 //Replacing the value with the inputs provided by the user in the editor.
530 body=m.replaceAll(copyMap.get(input));
532 response.setCharacterEncoding("UTF-8");
533 response.setContentType("application / json");
534 request.setCharacterEncoding("UTF-8");
536 PrintWriter out = response.getWriter();
537 String responseString = mapper.writeValueAsString(body);
538 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
539 out.write(j.toString());
541 } catch (Exception e) {
542 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);