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.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.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;
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;
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;
67 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
68 import org.openecomp.policy.common.logging.flexlogger.Logger;
72 public class CreateBRMSParamController extends RestrictedBaseController {
73 private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class);
75 private static CommonClassDao commonClassDao;
78 private CreateBRMSParamController(CommonClassDao commonClassDao){
79 CreateBRMSParamController.commonClassDao = commonClassDao;
82 public CreateBRMSParamController(){}
83 protected PolicyRestAdapter policyAdapter = null;
85 private HashMap<String, String> dynamicLayoutMap;
87 private static String brmsTemplateVlaue = "<$%BRMSParamTemplate=";
88 private static String String = "String";
91 @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
92 public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{
93 dynamicLayoutMap = new HashMap<>();
94 ObjectMapper mapper = new ObjectMapper();
95 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
96 JsonNode root = mapper.readTree(request.getReader());
97 String rule = findRule(root.get(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", ""));
99 response.setCharacterEncoding(PolicyController.getCharacterencoding());
100 response.setContentType(PolicyController.getContenttype());
101 request.setCharacterEncoding(PolicyController.getCharacterencoding());
103 PrintWriter out = response.getWriter();
104 String responseString = mapper.writeValueAsString(dynamicLayoutMap);
105 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
106 out.write(j.toString());
110 protected String findRule(String ruleTemplate) {
111 List<Object> datas = commonClassDao.getData(BRMSParamTemplate.class);
112 for (Object data: datas){
113 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) data;
114 if(bRMSParamTemplate.getRuleName().equals(ruleTemplate)){
115 return bRMSParamTemplate.getRule();
121 protected void generateUI(String rule) {
124 StringBuilder params = new StringBuilder("");
125 Boolean flag = false;
126 Boolean comment = false;
127 String lines[] = rule.split("\n");
128 for(String line : lines){
129 if (line.isEmpty() || line.startsWith("//")) {
132 if (line.startsWith("/*")) {
136 if (line.contains("//")) {
137 line = line.split("\\/\\/")[0];
139 if (line.contains("/*")) {
141 if (line.contains("*/")) {
144 line = line.split("\\/\\*")[0]
145 + line.split("\\*\\/")[1].replace("*/", "");
146 } catch (Exception e) {
147 policyLogger.info("Just for Logging"+e);
148 line = line.split("\\/\\*")[0];
151 line = line.split("\\/\\*")[0];
154 if (line.contains("*/")) {
157 line = line.split("\\*\\/")[1].replace("*/", "");
158 } catch (Exception e) {
159 policyLogger.info("Just for Logging"+e);
169 if (line.contains("declare Params")) {
173 if (line.contains("end") && flag) {
177 params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""));
178 String[] components = params.toString().split(":");
180 for (int i = 0; i < components.length; i++) {
183 caption = components[i];
185 if("".equals(caption)){
188 String nextComponent = "";
190 nextComponent = components[i + 1];
191 } catch (Exception e) {
192 policyLogger.info("Just for Logging"+e);
193 nextComponent = components[i];
195 if (nextComponent.startsWith(String)) {
197 createField(caption, type);
198 caption = nextComponent.replace(String, "");
199 } else if (nextComponent.startsWith("int")) {
201 createField(caption, type);
202 caption = nextComponent.replace("int", "");
205 } catch (Exception e) {
206 policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
211 private void createField(String caption, String type) {
212 dynamicLayoutMap.put(caption, type);
216 * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter.
217 * Which is used to bind the data in GUI
219 public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
220 dynamicLayoutMap = new HashMap<>();
221 if (policyAdapter.getPolicyData() instanceof PolicyType) {
222 PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
223 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
224 // policy name value is the policy name without any prefix and
226 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
227 if (policyLogger.isDebugEnabled()) {
228 policyLogger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
230 policyAdapter.setPolicyName(policyNameValue);
231 String description = "";
233 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
235 policyLogger.info("Just for Logging"+e);
236 description = policy.getDescription();
238 policyAdapter.setPolicyDescription(description);
239 setDataAdapterFromAdviceExpressions(policy, policyAdapter);
240 paramUIGenerate(policyAdapter, entity);
241 // Get the target data under policy.
242 policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
243 if(policyAdapter.getDynamicLayoutMap().size() > 0){
244 LinkedHashMap<String,String> drlRule = new LinkedHashMap<>();
245 for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
246 drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue));
248 policyAdapter.setRuleData(drlRule);
250 TargetType target = policy.getTarget();
251 if (target != null) {
252 setDataToAdapterFromTarget(target, policyAdapter);
257 private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){
258 ArrayList<Object> attributeList = new ArrayList<>();
260 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
261 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
262 for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
263 if(attributeAssignment.getAttributeId().startsWith("key:")){
264 Map<String, String> attribute = new HashMap<>();
265 String key = attributeAssignment.getAttributeId().replace("key:", "");
266 attribute.put("key", key);
267 @SuppressWarnings("unchecked")
268 JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
269 String value = (String) attributevalue.getValue().getContent().get(0);
270 attribute.put("value", value);
271 attributeList.add(attribute);
272 }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
273 ArrayList<String> dependencies = new ArrayList<>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
274 if(dependencies.contains("")){
275 dependencies.remove("");
277 policyAdapter.setBrmsDependency(dependencies);
278 }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
279 policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
282 policyAdapter.setAttributes(attributeList);
286 private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){
287 // Under target we have AnyOFType
288 List<AnyOfType> anyOfList = target.getAnyOf();
289 if (anyOfList != null) {
290 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
291 while (iterAnyOf.hasNext()) {
292 AnyOfType anyOf = iterAnyOf.next();
293 // Under AnyOFType we have AllOFType
294 List<AllOfType> allOfList = anyOf.getAllOf();
295 if (allOfList != null) {
296 Iterator<AllOfType> iterAllOf = allOfList.iterator();
297 while (iterAllOf.hasNext()) {
298 AllOfType allOf = iterAllOf.next();
299 // Under AllOFType we have Match
300 List<MatchType> matchList = allOf.getMatch();
301 if (matchList != null) {
302 setDataToAdapterFromMatchList(matchList, policyAdapter);
310 private void setDataToAdapterFromMatchList(List<MatchType> matchList, PolicyRestAdapter policyAdapter){
311 Iterator<MatchType> iterMatch = matchList.iterator();
312 while (iterMatch.hasNext()) {
313 MatchType match = iterMatch.next();
315 // Under the match we have attribute value and
316 // attributeDesignator. So,finally down to the actual attribute.
318 AttributeValueType attributeValue = match.getAttributeValue();
319 String value = (String) attributeValue.getContent().get(0);
320 AttributeDesignatorType designator = match.getAttributeDesignator();
321 String attributeId = designator.getAttributeId();
323 if ("RiskType".equals(attributeId)){
324 policyAdapter.setRiskType(value);
326 if ("RiskLevel".equals(attributeId)){
327 policyAdapter.setRiskLevel(value);
329 if ("guard".equals(attributeId)){
330 policyAdapter.setGuard(value);
332 if ("TTLDate".equals(attributeId) && !value.contains("NA")){
333 String newDate = convertDate(value, true);
334 policyAdapter.setTtlDate(newDate);
339 private String convertDate(String dateTTL, boolean portalType) {
340 String formateDate = null;
345 parts = dateTTL.split("-");
346 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
348 date = dateTTL.split("T");
349 parts = date[0].split("-");
350 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
354 // This method generates the UI from rule configuration
355 private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
356 String data = entity.getConfigurationData().getConfigBody();
359 StringBuilder params = new StringBuilder("");
360 Boolean flag = false;
361 Boolean comment = false;
362 for (String line : data.split("\n")) {
363 if (line.isEmpty() || line.startsWith("//")) {
366 if(line.contains(brmsTemplateVlaue)){
367 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
368 value = value.replace(brmsTemplateVlaue, "");
369 policyAdapter.setRuleName(value);
371 if (line.startsWith("/*")) {
375 if ((line.contains("//"))&&(!(line.contains("http://") || line.contains("https://")))){
376 line = line.split("\\/\\/")[0];
378 if (line.contains("/*")) {
380 if (line.contains("*/")) {
383 line = line.split("\\/\\*")[0]
384 + line.split("\\*\\/")[1].replace(
386 } catch (Exception e) {
387 policyLogger.info("Just for Logging"+e);
388 line = line.split("\\/\\*")[0];
391 line = line.split("\\/\\*")[0];
394 if (line.contains("*/")) {
397 line = line.split("\\*\\/")[1]
399 } catch (Exception e) {
400 policyLogger.info("Just for Logging"+e);
410 if (line.contains("rule") && line.contains(".Params\"")) {
414 if (line.contains("end") && flag) {
418 params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8));
419 params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
420 .replace("insert(params);end", "")
421 .replace("params.set", ""));
422 String[] components = params.toString().split("\\);");
423 if(components!= null && components.length > 0){
424 for (int i = 0; i < components.length; i++) {
426 components[i] = components[i]+")";
427 String caption = components[i].substring(0,
428 components[i].indexOf('('));
429 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
430 if (components[i].contains("(\"")) {
431 value = components[i]
432 .substring(components[i].indexOf("(\""),
433 components[i].indexOf("\")"))
434 .replace("(\"", "").replace("\")", "");
436 value = components[i]
437 .substring(components[i].indexOf('('),
438 components[i].indexOf(')'))
439 .replace("(", "").replace(")", "");
441 dynamicLayoutMap.put(caption, value);
445 } catch (Exception e) {
446 policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e);
453 @SuppressWarnings("unchecked")
454 @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
455 public ModelAndView setViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{
457 ObjectMapper mapper = new ObjectMapper();
458 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
459 JsonNode root = mapper.readTree(request.getReader());
460 PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class);
461 policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", ""));
462 if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){
463 policyData.setEditPolicy(true);
468 body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
469 brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n";
470 body = body + findRule((String) policyData.getRuleName()) + "\n";
471 StringBuilder generatedRule = new StringBuilder();
472 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();");
474 if(policyData.getRuleData().size() > 0){
475 for(Object keyValue: policyData.getRuleData().keySet()){
476 String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
477 if (String.equals(keyValue)) {
478 generatedRule.append("\n\t\tparams.set"
480 + policyData.getRuleData().get(keyValue).toString() + "\");");
482 generatedRule.append("\n\t\tparams.set"
484 + policyData.getRuleData().get(keyValue).toString() + ");");
488 generatedRule.append("\n\t\tinsert(params);\nend");
489 policyLogger.info("New rule generated with :" + generatedRule.toString());
490 body = body + generatedRule.toString();
492 Map<String,String> copyMap=new HashMap<>();
493 copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
494 copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
495 copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
496 copyMap.put("policyVersion", "1");
497 //Finding all the keys in the Map data-structure.
498 Set<String> keySet= copyMap.keySet();
499 Iterator<String> iterator = keySet.iterator();
502 while(iterator.hasNext()) {
503 //Converting the first character of the key into a lower case.
504 String input= iterator.next();
505 String output = Character.toLowerCase(input.charAt(0)) +
506 (input.length() > 1 ? input.substring(1) : "");
507 //Searching for a pattern in the String using the key.
508 p=Pattern.compile("\\$\\{"+output+"\\}");
510 //Replacing the value with the inputs provided by the user in the editor.
511 body=m.replaceAll(copyMap.get(input));
513 response.setCharacterEncoding("UTF-8");
514 response.setContentType("application / json");
515 request.setCharacterEncoding("UTF-8");
517 PrintWriter out = response.getWriter();
518 String responseString = mapper.writeValueAsString(body);
519 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
520 out.write(j.toString());
522 } catch (Exception e) {
523 policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);