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.AttributeValueType;
61 import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType;
62 import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType;
63 import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType;
64 import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType;
66 import org.openecomp.policy.common.logging.flexlogger.FlexLogger;
67 import org.openecomp.policy.common.logging.flexlogger.Logger;
71 public class CreateBRMSParamController extends RestrictedBaseController {
72 private static final Logger logger = FlexLogger.getLogger(CreateBRMSParamController.class);
74 private static CommonClassDao commonClassDao;
77 private CreateBRMSParamController(CommonClassDao commonClassDao){
78 CreateBRMSParamController.commonClassDao = commonClassDao;
81 public CreateBRMSParamController(){}
82 protected PolicyRestAdapter policyAdapter = null;
83 private ArrayList<Object> attributeList;
85 private HashMap<String, String> dynamicLayoutMap;
88 @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
89 public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{
90 dynamicLayoutMap = new HashMap<String, String>();
91 ObjectMapper mapper = new ObjectMapper();
92 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
93 JsonNode root = mapper.readTree(request.getReader());
94 String rule = findRule(root.get("policyData").toString().replaceAll("^\"|\"$", ""));
96 response.setCharacterEncoding("UTF-8");
97 response.setContentType("application / json");
98 request.setCharacterEncoding("UTF-8");
100 PrintWriter out = response.getWriter();
101 String responseString = mapper.writeValueAsString(dynamicLayoutMap);
102 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
103 out.write(j.toString());
107 protected String findRule(String ruleTemplate) {
108 List<Object> datas = commonClassDao.getData(BRMSParamTemplate.class);
109 for (Object data: datas){
110 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) data;
111 if(bRMSParamTemplate.getRuleName().equals(ruleTemplate)){
112 return bRMSParamTemplate.getRule();
118 protected void generateUI(String rule) {
122 Boolean flag = false;
123 Boolean comment = false;
124 String lines[] = rule.split("\n");
125 for(String line : lines){
126 if (line.isEmpty() || line.startsWith("//")) {
129 if (line.startsWith("/*")) {
133 if (line.contains("//")) {
134 line = line.split("\\/\\/")[0];
136 if (line.contains("/*")) {
138 if (line.contains("*/")) {
141 line = line.split("\\/\\*")[0]
142 + line.split("\\*\\/")[1].replace("*/", "");
143 } catch (Exception e) {
144 line = line.split("\\/\\*")[0];
147 line = line.split("\\/\\*")[0];
150 if (line.contains("*/")) {
153 line = line.split("\\*\\/")[1].replace("*/", "");
154 } catch (Exception e) {
162 params = params + line;
164 if (line.contains("declare Params")) {
165 params = params + line;
168 if (line.contains("end") && flag) {
172 params = params.replace("declare Params", "").replace("end", "")
173 .replaceAll("\\s+", "");
174 String[] components = params.split(":");
176 for (int i = 0; i < components.length; i++) {
179 caption = components[i];
181 if(caption.equals("")){
184 String nextComponent = "";
186 nextComponent = components[i + 1];
187 } catch (Exception e) {
188 nextComponent = components[i];
190 if (nextComponent.startsWith("String")) {
192 createField(caption, type);
193 caption = nextComponent.replace("String", "");
194 } else if (nextComponent.startsWith("int")) {
196 createField(caption, type);
197 caption = nextComponent.replace("int", "");
200 } catch (Exception e) {
201 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
206 private void createField(String caption, String type) {
207 dynamicLayoutMap.put(caption, type);
211 @SuppressWarnings("unchecked")
212 public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
213 attributeList = new ArrayList<Object>();
214 dynamicLayoutMap = new HashMap<String, String>();
215 if (policyAdapter.getPolicyData() instanceof PolicyType) {
216 PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
217 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
218 // policy name value is the policy name without any prefix and
220 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
221 if (logger.isDebugEnabled()) {
222 logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
224 policyAdapter.setPolicyName(policyNameValue);
225 String description = "";
227 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
229 description = policy.getDescription();
231 policyAdapter.setPolicyDescription(description);
233 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
234 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
235 for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
236 if(attributeAssignment.getAttributeId().startsWith("key:")){
237 Map<String, String> attribute = new HashMap<String, String>();
238 String key = attributeAssignment.getAttributeId().replace("key:", "");
239 attribute.put("key", key);
240 JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
241 String value = (String) attributevalue.getValue().getContent().get(0);
242 attribute.put("value", value);
243 attributeList.add(attribute);
244 }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
245 ArrayList<String> dependencies = new ArrayList<String>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
246 if(dependencies.contains("")){
247 dependencies.remove("");
249 policyAdapter.setBrmsDependency(dependencies);
250 }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
251 policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
254 policyAdapter.setAttributes(attributeList);
256 paramUIGenerate(policyAdapter, entity);
257 // Get the target data under policy.
258 policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
259 if(policyAdapter.getDynamicLayoutMap().size() > 0){
260 LinkedHashMap<String,String> drlRule = new LinkedHashMap<String, String>();
261 for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
262 drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue).toString());
264 policyAdapter.setRuleData(drlRule);
266 TargetType target = policy.getTarget();
267 if (target != null) {
268 // Under target we have AnyOFType
269 List<AnyOfType> anyOfList = target.getAnyOf();
270 if (anyOfList != null) {
271 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
272 while (iterAnyOf.hasNext()) {
273 AnyOfType anyOf = iterAnyOf.next();
274 // Under AnyOFType we have AllOFType
275 List<AllOfType> allOfList = anyOf.getAllOf();
276 if (allOfList != null) {
277 Iterator<AllOfType> iterAllOf = allOfList.iterator();
279 while (iterAllOf.hasNext()) {
280 AllOfType allOf = iterAllOf.next();
281 // Under AllOFType we have Match
282 List<MatchType> matchList = allOf.getMatch();
283 if (matchList != null) {
284 Iterator<MatchType> iterMatch = matchList.iterator();
285 while (iterMatch.hasNext()) {
286 MatchType match = iterMatch.next();
288 // Under the match we have attributevalue and
289 // attributeDesignator. So,finally down to the actual attribute.
291 AttributeValueType attributeValue = match.getAttributeValue();
292 String value = (String) attributeValue.getContent().get(0);
295 policyAdapter.setRiskType(value);
299 policyAdapter.setRiskLevel(value);
303 policyAdapter.setGuard(value);
305 if (index == 6 && !value.contains("NA")){
306 String newDate = convertDate(value, true);
307 policyAdapter.setTtlDate(newDate);
321 private String convertDate(String dateTTL, boolean portalType) {
322 String formateDate = null;
327 parts = dateTTL.split("-");
328 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
330 date = dateTTL.split("T");
331 parts = date[0].split("-");
332 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
336 // This method generates the UI from rule configuration
337 private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
338 String data = entity.getConfigurationData().getConfigBody();
342 Boolean flag = false;
343 Boolean comment = false;
344 for (String line : data.split("\n")) {
345 if (line.isEmpty() || line.startsWith("//")) {
348 if(line.contains("<$%BRMSParamTemplate=")){
349 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
350 value = value.replace("<$%BRMSParamTemplate=", "");
351 policyAdapter.setRuleName(value);
353 if (line.startsWith("/*")) {
357 if (line.contains("//")) {
358 if(!(line.contains("http://") || line.contains("https://"))){
359 line = line.split("\\/\\/")[0];
362 if (line.contains("/*")) {
364 if (line.contains("*/")) {
367 line = line.split("\\/\\*")[0]
368 + line.split("\\*\\/")[1].replace(
370 } catch (Exception e) {
371 line = line.split("\\/\\*")[0];
374 line = line.split("\\/\\*")[0];
377 if (line.contains("*/")) {
380 line = line.split("\\*\\/")[1]
382 } catch (Exception e) {
390 params = params + line;
392 if (line.contains("rule") && line.contains(".Params\"")) {
393 params = params + line;
396 if (line.contains("end") && flag) {
400 params = params.substring(params.indexOf(".Params\"")+ 8);
401 params = params.replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
402 .replace("insert(params);end", "")
403 .replace("params.set", "");
404 String[] components = params.split(";");
405 if(components!= null && components.length > 0){
406 for (int i = 0; i < components.length; i++) {
408 String caption = components[i].substring(0,
409 components[i].indexOf("("));
410 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
411 if (components[i].contains("(\"")) {
412 value = components[i]
413 .substring(components[i].indexOf("(\""),
414 components[i].indexOf("\")"))
415 .replace("(\"", "").replace("\")", "");
417 value = components[i]
418 .substring(components[i].indexOf("("),
419 components[i].indexOf(")"))
420 .replace("(", "").replace(")", "");
422 dynamicLayoutMap.put(caption, value);
426 } catch (Exception e) {
427 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage());
434 @SuppressWarnings("unchecked")
435 @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
436 public ModelAndView setViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{
438 ObjectMapper mapper = new ObjectMapper();
439 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
440 JsonNode root = mapper.readTree(request.getReader());
441 PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
442 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
443 if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
444 policyData.isEditPolicy = true;
449 body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
450 "<$%BRMSParamTemplate=" + policyData.getRuleName() + "%$> \n */ \n";
451 body = body + findRule((String) policyData.getRuleName()) + "\n";
452 String generatedRule = "rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();";
454 if(policyData.getRuleData().size() > 0){
455 for(Object keyValue: policyData.getRuleData().keySet()){
456 String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
457 if (keyValue.equals("String")) {
458 generatedRule = generatedRule + "\n\t\tparams.set"
460 + policyData.getRuleData().get(keyValue).toString() + "\");";
462 generatedRule = generatedRule + "\n\t\tparams.set"
464 + policyData.getRuleData().get(keyValue).toString() + ");";
468 generatedRule = generatedRule
469 + "\n\t\tinsert(params);\nend";
470 logger.info("New rule generated with :" + generatedRule);
471 body = body + generatedRule;
473 Map<String,String> copyMap=new HashMap<>();
474 copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
475 copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
476 copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
477 copyMap.put("policyVersion", "1");
478 //Finding all the keys in the Map data-structure.
479 Set<String> keySet= copyMap.keySet();
480 Iterator<String> iterator = keySet.iterator();
483 while(iterator.hasNext()) {
484 //Converting the first character of the key into a lower case.
485 String input= iterator.next();
486 String output = Character.toLowerCase(input.charAt(0)) +
487 (input.length() > 1 ? input.substring(1) : "");
488 //Searching for a pattern in the String using the key.
489 p=Pattern.compile("\\$\\{"+output+"\\}");
491 //Replacing the value with the inputs provided by the user in the editor.
492 body=m.replaceAll(copyMap.get(input));
494 response.setCharacterEncoding("UTF-8");
495 response.setContentType("application / json");
496 request.setCharacterEncoding("UTF-8");
498 PrintWriter out = response.getWriter();
499 String responseString = mapper.writeValueAsString(body);
500 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
501 out.write(j.toString());
503 } catch (Exception e) {
504 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);