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 logger = 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;
84 private ArrayList<Object> attributeList;
86 private HashMap<String, String> dynamicLayoutMap;
89 @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
90 public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{
91 dynamicLayoutMap = new HashMap<>();
92 ObjectMapper mapper = new ObjectMapper();
93 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
94 JsonNode root = mapper.readTree(request.getReader());
95 String rule = findRule(root.get("policyData").toString().replaceAll("^\"|\"$", ""));
97 response.setCharacterEncoding("UTF-8");
98 response.setContentType("application / json");
99 request.setCharacterEncoding("UTF-8");
101 PrintWriter out = response.getWriter();
102 String responseString = mapper.writeValueAsString(dynamicLayoutMap);
103 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
104 out.write(j.toString());
108 protected String findRule(String ruleTemplate) {
109 List<Object> datas = commonClassDao.getData(BRMSParamTemplate.class);
110 for (Object data: datas){
111 BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) data;
112 if(bRMSParamTemplate.getRuleName().equals(ruleTemplate)){
113 return bRMSParamTemplate.getRule();
119 protected void generateUI(String rule) {
123 Boolean flag = false;
124 Boolean comment = false;
125 String lines[] = rule.split("\n");
126 for(String line : lines){
127 if (line.isEmpty() || line.startsWith("//")) {
130 if (line.startsWith("/*")) {
134 if (line.contains("//")) {
135 line = line.split("\\/\\/")[0];
137 if (line.contains("/*")) {
139 if (line.contains("*/")) {
142 line = line.split("\\/\\*")[0]
143 + line.split("\\*\\/")[1].replace("*/", "");
144 } catch (Exception e) {
145 line = line.split("\\/\\*")[0];
148 line = line.split("\\/\\*")[0];
151 if (line.contains("*/")) {
154 line = line.split("\\*\\/")[1].replace("*/", "");
155 } catch (Exception e) {
163 params = params + line;
165 if (line.contains("declare Params")) {
166 params = params + line;
169 if (line.contains("end") && flag) {
173 params = params.replace("declare Params", "").replace("end", "")
174 .replaceAll("\\s+", "");
175 String[] components = params.split(":");
177 for (int i = 0; i < components.length; i++) {
180 caption = components[i];
182 if(caption.equals("")){
185 String nextComponent = "";
187 nextComponent = components[i + 1];
188 } catch (Exception e) {
189 nextComponent = components[i];
191 if (nextComponent.startsWith("String")) {
193 createField(caption, type);
194 caption = nextComponent.replace("String", "");
195 } else if (nextComponent.startsWith("int")) {
197 createField(caption, type);
198 caption = nextComponent.replace("int", "");
201 } catch (Exception e) {
202 logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e);
207 private void createField(String caption, String type) {
208 dynamicLayoutMap.put(caption, type);
212 @SuppressWarnings("unchecked")
213 public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
214 attributeList = new ArrayList<>();
215 dynamicLayoutMap = new HashMap<>();
216 if (policyAdapter.getPolicyData() instanceof PolicyType) {
217 PolicyType policy = (PolicyType) policyAdapter.getPolicyData();
218 policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName());
219 // policy name value is the policy name without any prefix and
221 String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") + 11);
222 if (logger.isDebugEnabled()) {
223 logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName());
225 policyAdapter.setPolicyName(policyNameValue);
226 String description = "";
228 description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:"));
230 description = policy.getDescription();
232 policyAdapter.setPolicyDescription(description);
234 AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions();
235 for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){
236 for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){
237 if(attributeAssignment.getAttributeId().startsWith("key:")){
238 Map<String, String> attribute = new HashMap<>();
239 String key = attributeAssignment.getAttributeId().replace("key:", "");
240 attribute.put("key", key);
241 JAXBElement<AttributeValueType> attributevalue = (JAXBElement<AttributeValueType>) attributeAssignment.getExpression();
242 String value = (String) attributevalue.getValue().getContent().get(0);
243 attribute.put("value", value);
244 attributeList.add(attribute);
245 }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){
246 ArrayList<String> dependencies = new ArrayList<String>(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(",")));
247 if(dependencies.contains("")){
248 dependencies.remove("");
250 policyAdapter.setBrmsDependency(dependencies);
251 }else if(attributeAssignment.getAttributeId().startsWith("controller:")){
252 policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", ""));
255 policyAdapter.setAttributes(attributeList);
257 paramUIGenerate(policyAdapter, entity);
258 // Get the target data under policy.
259 policyAdapter.setDynamicLayoutMap(dynamicLayoutMap);
260 if(policyAdapter.getDynamicLayoutMap().size() > 0){
261 LinkedHashMap<String,String> drlRule = new LinkedHashMap<>();
262 for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){
263 drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue).toString());
265 policyAdapter.setRuleData(drlRule);
267 TargetType target = policy.getTarget();
268 if (target != null) {
269 // Under target we have AnyOFType
270 List<AnyOfType> anyOfList = target.getAnyOf();
271 if (anyOfList != null) {
272 Iterator<AnyOfType> iterAnyOf = anyOfList.iterator();
273 while (iterAnyOf.hasNext()) {
274 AnyOfType anyOf = iterAnyOf.next();
275 // Under AnyOFType we have AllOFType
276 List<AllOfType> allOfList = anyOf.getAllOf();
277 if (allOfList != null) {
278 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 attribute value and
289 // attributeDesignator. So,finally down to the actual attribute.
291 AttributeValueType attributeValue = match.getAttributeValue();
292 String value = (String) attributeValue.getContent().get(0);
293 AttributeDesignatorType designator = match.getAttributeDesignator();
294 String attributeId = designator.getAttributeId();
296 if (attributeId.equals("RiskType")){
297 policyAdapter.setRiskType(value);
299 if (attributeId.equals("RiskLevel")){
300 policyAdapter.setRiskLevel(value);
302 if (attributeId.equals("guard")){
303 policyAdapter.setGuard(value);
305 if (attributeId.equals("TTLDate") && !value.contains("NA")){
306 String newDate = convertDate(value, true);
307 policyAdapter.setTtlDate(newDate);
319 private String convertDate(String dateTTL, boolean portalType) {
320 String formateDate = null;
325 parts = dateTTL.split("-");
326 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z";
328 date = dateTTL.split("T");
329 parts = date[0].split("-");
330 formateDate = parts[2] + "-" + parts[1] + "-" + parts[0];
334 // This method generates the UI from rule configuration
335 private void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
336 String data = entity.getConfigurationData().getConfigBody();
340 Boolean flag = false;
341 Boolean comment = false;
342 for (String line : data.split("\n")) {
343 if (line.isEmpty() || line.startsWith("//")) {
346 if(line.contains("<$%BRMSParamTemplate=")){
347 String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>"));
348 value = value.replace("<$%BRMSParamTemplate=", "");
349 policyAdapter.setRuleName(value);
351 if (line.startsWith("/*")) {
355 if (line.contains("//")) {
356 if(!(line.contains("http://") || line.contains("https://"))){
357 line = line.split("\\/\\/")[0];
360 if (line.contains("/*")) {
362 if (line.contains("*/")) {
365 line = line.split("\\/\\*")[0]
366 + line.split("\\*\\/")[1].replace(
368 } catch (Exception e) {
369 line = line.split("\\/\\*")[0];
372 line = line.split("\\/\\*")[0];
375 if (line.contains("*/")) {
378 line = line.split("\\*\\/")[1]
380 } catch (Exception e) {
388 params = params + line;
390 if (line.contains("rule") && line.contains(".Params\"")) {
391 params = params + line;
394 if (line.contains("end") && flag) {
398 params = params.substring(params.indexOf(".Params\"")+ 8);
399 params = params.replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","")
400 .replace("insert(params);end", "")
401 .replace("params.set", "");
402 String[] components = params.split(";");
403 if(components!= null && components.length > 0){
404 for (int i = 0; i < components.length; i++) {
406 String caption = components[i].substring(0,
407 components[i].indexOf("("));
408 caption = caption.substring(0, 1).toLowerCase() + caption.substring(1);
409 if (components[i].contains("(\"")) {
410 value = components[i]
411 .substring(components[i].indexOf("(\""),
412 components[i].indexOf("\")"))
413 .replace("(\"", "").replace("\")", "");
415 value = components[i]
416 .substring(components[i].indexOf("("),
417 components[i].indexOf(")"))
418 .replace("(", "").replace(")", "");
420 dynamicLayoutMap.put(caption, value);
424 } catch (Exception e) {
425 logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage());
432 @SuppressWarnings("unchecked")
433 @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST})
434 public ModelAndView setViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{
436 ObjectMapper mapper = new ObjectMapper();
437 mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
438 JsonNode root = mapper.readTree(request.getReader());
439 PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class);
440 policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", ""));
441 if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){
442 policyData.isEditPolicy = true;
447 body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " +
448 "<$%BRMSParamTemplate=" + policyData.getRuleName() + "%$> \n */ \n";
449 body = body + findRule((String) policyData.getRuleName()) + "\n";
450 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();";
452 if(policyData.getRuleData().size() > 0){
453 for(Object keyValue: policyData.getRuleData().keySet()){
454 String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1);
455 if (keyValue.equals("String")) {
456 generatedRule = generatedRule + "\n\t\tparams.set"
458 + policyData.getRuleData().get(keyValue).toString() + "\");";
460 generatedRule = generatedRule + "\n\t\tparams.set"
462 + policyData.getRuleData().get(keyValue).toString() + ");";
466 generatedRule = generatedRule
467 + "\n\t\tinsert(params);\nend";
468 logger.info("New rule generated with :" + generatedRule);
469 body = body + generatedRule;
471 Map<String,String> copyMap=new HashMap<>();
472 copyMap.putAll((Map<? extends String, ? extends String>) policyData.getRuleData());
473 copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName());
474 copyMap.put("policyScope", policyData.getDomainDir().replace("\\", "."));
475 copyMap.put("policyVersion", "1");
476 //Finding all the keys in the Map data-structure.
477 Set<String> keySet= copyMap.keySet();
478 Iterator<String> iterator = keySet.iterator();
481 while(iterator.hasNext()) {
482 //Converting the first character of the key into a lower case.
483 String input= iterator.next();
484 String output = Character.toLowerCase(input.charAt(0)) +
485 (input.length() > 1 ? input.substring(1) : "");
486 //Searching for a pattern in the String using the key.
487 p=Pattern.compile("\\$\\{"+output+"\\}");
489 //Replacing the value with the inputs provided by the user in the editor.
490 body=m.replaceAll(copyMap.get(input));
492 response.setCharacterEncoding("UTF-8");
493 response.setContentType("application / json");
494 request.setCharacterEncoding("UTF-8");
496 PrintWriter out = response.getWriter();
497 String responseString = mapper.writeValueAsString(body);
498 JSONObject j = new JSONObject("{policyData: " + responseString + "}");
499 out.write(j.toString());
501 } catch (Exception e) {
502 logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e);