From 91d04c64771832a0b8815ffbe1f0f9920320d94d Mon Sep 17 00:00:00 2001 From: Pamela Dragosh Date: Tue, 14 Feb 2017 19:41:00 -0500 Subject: Initial OpenECOMP policy/engine commit Change-Id: I7dbff37733b661643dd4d1caefa3d7dccc361b6e Signed-off-by: Pamela Dragosh --- .../policy/controller/ActionPolicyController.java | 535 ++++++++ .../policy/controller/AdminTabController.java | 100 ++ .../policy/controller/AutoPushController.java | 433 +++++++ .../controller/CreateBRMSParamController.java | 723 +++++++++++ .../policy/controller/CreateBRMSRawController.java | 440 +++++++ .../CreateClosedLoopFaultController.java | 889 ++++++++++++++ .../controller/CreateClosedLoopPMController.java | 422 +++++++ .../CreateDcaeMicroServiceController.java | 987 +++++++++++++++ .../controller/CreateFirewallController.java | 1292 ++++++++++++++++++++ .../policy/controller/CreatePolicyController.java | 484 ++++++++ .../policy/controller/DashboardController.java | 430 +++++++ .../controller/DecisionPolicyController.java | 507 ++++++++ .../openecomp/policy/controller/PDPController.java | 302 +++++ .../policy/controller/PolicyController.java | 418 +++++++ .../PolicyExportAndImportController.java | 563 +++++++++ .../controller/PolicyNotificationController.java | 122 ++ .../policy/controller/PolicyRolesController.java | 137 +++ .../controller/PolicyValidationController.java | 300 +++++ 18 files changed, 9084 insertions(+) create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AdminTabController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AutoPushController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DashboardController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PDPController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java (limited to 'ecomp-sdk-app/src/main/java/org/openecomp/policy/controller') diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java new file mode 100644 index 000000000..0688846b4 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java @@ -0,0 +1,535 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.FunctionDefinitionDao; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.dao.ActionPolicyDictDao; +import org.openecomp.policy.rest.jpa.ActionPolicyDict; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping({"/"}) +public class ActionPolicyController extends RestrictedBaseController{ + private static final Logger logger = FlexLogger.getLogger(ActionPolicyController.class); + + private static FunctionDefinitionDao functionDefinitionDao; + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static ActionPolicyDictDao actionPolciyDictDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private ActionPolicyController(RuleAlgorithmsDao ruleAlgorithmsDao, ActionPolicyDictDao actionPolciyDictDao, + PolicyVersionDao policyVersionDao, FunctionDefinitionDao functionDefinitionDao, WatchPolicyNotificationDao policyNotificationDao){ + ActionPolicyController.ruleAlgorithmsDao =ruleAlgorithmsDao; + ActionPolicyController.actionPolciyDictDao =actionPolciyDictDao; + ActionPolicyController.policyVersionDao =policyVersionDao; + ActionPolicyController.functionDefinitionDao = functionDefinitionDao; + ActionPolicyController.policyNotificationDao = policyNotificationDao; + } + + public ActionPolicyController(){} + + private String ruleID = ""; + private ArrayList attributeList; + protected LinkedList ruleAlgoirthmTracker; + public static final String PERFORMER_ATTRIBUTEID = "performer"; + protected Map performer = new HashMap(); + private ArrayList ruleAlgorithmList; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + + @RequestMapping(value={"/get_FunctionDefinitionDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getFunctionDefinitionData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("functionDefinitionDatas", mapper.writeValueAsString(functionDefinitionDao.getFunctionDefinitionByName())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + logger.equals(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while retriving the Function Definition data"+e); + } + } + + @RequestMapping(value={"/policyController/save_Actionpolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveActionPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Action_" + policyData.getPolicyName(); + List versionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map successMap = new HashMap(); + Map attributeMap = new HashMap(); + + List dynamicRuleAlgorithmLabels = new LinkedList(); + List dynamicRuleAlgorithmCombo = new LinkedList(); + List dynamicRuleAlgorithmField1 = new LinkedList(); + List dynamicRuleAlgorithmField2 = new LinkedList(); + + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + String value = ((LinkedHashMap) attribute).get("number").toString(); + attributeMap.put(key, value); + } + } + } + + if(policyData.getRuleAlgorithmschoices().size() > 0){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap){ + String label = ((LinkedHashMap) attribute).get("id").toString(); + String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); + dynamicRuleAlgorithmLabels.add(label); + dynamicRuleAlgorithmField1.add(key); + dynamicRuleAlgorithmCombo.add(rule); + dynamicRuleAlgorithmField2.add(value); + } + } + } + + String actionDictValue = policyData.getActionAttributeValue(); + ActionPolicyDict jsonData = ((ActionPolicyDict) actionPolciyDictDao.getActionEntityDatabyId(actionDictValue)); + String actionBodyString = jsonData.getBody(); + String actionDictHeader = jsonData.getHeader(); + String actionDictType = jsonData.getType(); + String actionDictUrl = jsonData.getUrl(); + String actionDictMethod = jsonData.getMethod(); + policyData.setActionDictHeader(actionDictHeader); + policyData.setActionDictType(actionDictType); + policyData.setActionDictUrl(actionDictUrl); + policyData.setActionDictMethod(actionDictMethod); + policyData.setActionAttribute(actionDictValue); + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); + policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + if (actionBodyString != null) { + policyData.setActionBody(actionBodyString); + } + policyData.setDynamicFieldConfigAttributes(attributeMap); + + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List policyVersionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + public void PrePopulateActionPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList(); + ruleAlgorithmList = new ArrayList(); + performer.put("PDP", "PDPAction"); + performer.put("PEP", "PEPAction"); + + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1, policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target != null) { + // under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AntOfType we have AllOfType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOfType we have Mathch. + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic componet at index 0. + Map attribute = new HashMap(); + attribute.put("option", attributeId); + attribute.put("number", value); + attributeList.add(attribute); + } + } + policyAdapter.setAttributes(attributeList); + } + } + } + } + + List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + // Under rule we have Condition and obligation. + for (Object o : ruleList) { + if (o instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + ruleID = ((RuleType) o).getRuleId(); + ConditionType condition = ((RuleType) o).getCondition(); + ObligationExpressionsType obligations = ((RuleType) o).getObligationExpressions(); + if (condition != null) { + int index = 0; + ApplyType actionApply = (ApplyType) condition.getExpression().getValue(); + ruleAlgoirthmTracker = new LinkedList(); + // Populating Rule Algorithms starting from compound. + prePopulateCompoundRuleAlgorithm(index, actionApply); + } + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + // get the Obligation data under the rule for Form elements. + if (obligations != null) { + // Under the obligationExpressions we have obligationExpression. + List obligationList = obligations.getObligationExpression(); + if (obligationList != null) { + Iterator iterObligation = obligationList.iterator(); + while (iterObligation.hasNext()) { + ObligationExpressionType obligation = iterObligation.next(); + policyAdapter.setActionAttributeValue(obligation.getObligationId()); + // Under the obligationExpression we have attributeAssignmentExpression. + List attributeAssignmentExpressionList = obligation.getAttributeAssignmentExpression(); + if (attributeAssignmentExpressionList != null) { + Iterator iterAttributeAssignmentExpression = attributeAssignmentExpressionList.iterator(); + while (iterAttributeAssignmentExpression.hasNext()) { + AttributeAssignmentExpressionType attributeAssignmentExpression = iterAttributeAssignmentExpression.next(); + String attributeID = attributeAssignmentExpression.getAttributeId(); + AttributeValueType attributeValue = (AttributeValueType) attributeAssignmentExpression.getExpression().getValue(); + if (attributeID.equals(PERFORMER_ATTRIBUTEID)) { + for (String key : performer.keySet()) { + String keyValue = performer.get(key); + if (keyValue.equals(attributeValue.getContent().get(0))) { + policyAdapter.setActionPerformer(key); + } + } + } + } + } + } + } + } + } + } + } + } + } + + private int prePopulateCompoundRuleAlgorithm(int index, ApplyType actionApply) { + boolean isCompoundRule = true; + List> jaxbActionTypes = actionApply.getExpression(); + for (JAXBElement jaxbElement : jaxbActionTypes) { + // If There is Attribute Value under Action Type that means we came to the final child + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating rule algoirthm: " + index); + } + // Check to see if Attribute Value exists, if yes then it is not a compound rule + if (jaxbElement.getValue() instanceof AttributeValueType) { + prePopulateRuleAlgorithms(index, actionApply, jaxbActionTypes); + ruleAlgoirthmTracker.addLast(index); + isCompoundRule = false; + index++; + } + } + if (isCompoundRule) { + // As it's compound rule, Get the Apply types + for (JAXBElement jaxbElement : jaxbActionTypes) { + ApplyType innerActionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateCompoundRuleAlgorithm(index, innerActionApply); + } + // Populate combo box + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating Compound rule algorithm: " + index); + } + Map rule = new HashMap(); + for (String key : PolicyController.getDropDownMap().keySet()) { + String keyValue = PolicyController.getDropDownMap().get(key); + if (keyValue.equals(actionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", key); + } + } + rule.put("id", "A" + (index +1)); + // Populate Key and values for Compound Rule + rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); + ruleAlgoirthmTracker.removeLast(); + rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmList.add(rule); + index++; + } + return index; + } + + private void prePopulateRuleAlgorithms(int index, ApplyType actionApply, List> jaxbActionTypes) { + Map ruleMap = new HashMap(); + ruleMap.put("id", "A" + (index +1)); + // Populate combo box + Map dropDownMap = PolicyController.getDropDownMap(); + for (String key : dropDownMap.keySet()) { + String keyValue = dropDownMap.get(key); + if (keyValue.equals(actionApply.getFunctionId())) { + ruleMap.put("dynamicRuleAlgorithmCombo", key); + } + } + // Populate the key and value fields + // Rule Attribute added as key + if ((jaxbActionTypes.get(0).getValue()) instanceof ApplyType) { + // Get from Attribute Designator + ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(0).getValue(); + List> jaxbInnerActionTypes = innerActionApply.getExpression(); + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(1).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + // Rule Attribute added as value + else if (((jaxbActionTypes.get(0).getValue()) instanceof AttributeValueType)) { + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbActionTypes.get(0).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + + ApplyType innerActionApply = (ApplyType) jaxbActionTypes.get(1).getValue(); + List> jaxbInnerActionTypes = innerActionApply.getExpression(); + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerActionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + } + ruleAlgorithmList.add(ruleMap); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AdminTabController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AdminTabController.java new file mode 100644 index 000000000..67c2d3080 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AdminTabController.java @@ -0,0 +1,100 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.PrintWriter; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.dao.GlobalRoleSettingsDao; +import org.openecomp.policy.rest.jpa.GlobalRoleSettings; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class AdminTabController extends RestrictedBaseController{ + + @Autowired + GlobalRoleSettingsDao globalRoleSettingsDao; + + + + @RequestMapping(value={"/get_LockDownData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getAdminTabEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("lockdowndata", mapper.writeValueAsString(globalRoleSettingsDao.getGlobalRoleSettings())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/adminTabController/save_LockDownValue.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + GlobalRoleSettings globalRole = mapper.readValue(root.get("lockdowndata").toString(), GlobalRoleSettings.class); + globalRole.setRole("super-admin"); + globalRoleSettingsDao.update(globalRole); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(this.globalRoleSettingsDao.getGlobalRoleSettings()); + JSONObject j = new JSONObject("{descriptiveScopeDictionaryDatas: " + responseString + "}"); + + out.write(j.toString()); + + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AutoPushController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AutoPushController.java new file mode 100644 index 000000000..699d8ed00 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/AutoPushController.java @@ -0,0 +1,433 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.FilenameUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.policy.adapter.AutoPushTabAdapter; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.policy.model.PDPPolicyContainer; +import org.openecomp.policy.model.Roles; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; + +import com.att.research.xacml.api.pap.PAPException; +//import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDPGroup; +import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Controller +@RequestMapping({"/"}) +public class AutoPushController extends RestrictedBaseController{ + + private static final Logger logger = FlexLogger.getLogger(AutoPushController.class); + + private PDPGroupContainer container; + protected List groups = Collections.synchronizedList(new ArrayList()); + + private static PDPPolicyContainer policyContainer; + Set selectedPolicies; + + @Autowired + PolicyVersionDao policyVersionDao; + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + } + + } + } + + @RequestMapping(value={"/get_AutoPushPoliciesContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyGroupContainerData(HttpServletRequest request, HttpServletResponse response){ + try{ + Path gitPath = PolicyController.getGitPath().toAbsolutePath(); + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{data: " + readFileRepository(gitPath,0,0,request).toString() + "}"); + out.write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @SuppressWarnings("rawtypes") + public JSONArray readFileRepository(Path path, int id, int parentid, HttpServletRequest request){ + Set scopes = null; + List roles = null; + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + logger.error("Exception Occured while reading userid from cookie" +e); + } + JSONArray fileJSONArray = new JSONArray(); + File root = new File(path.toString()); + if(parentid==0 ){ + parentid = 1; + } + List userRoles = PolicyController.getRoles(userId); + roles = new ArrayList(); + scopes = new HashSet(); + for(Roles userRole: userRoles){ + roles.add(userRole.getRole()); + scopes.add(userRole.getScope()); + } + + for ( File file : root.listFiles()){ + if (!(file.toString().contains(".git") || file.equals(".DS_Store"))) { + if(file.isDirectory()){ + JSONObject el = new JSONObject(); + String fileName = file.getName().toString(); + el.put("categoryId", id+1); + el.put("name", fileName); + el.put("dateModified", lastModified(file)); + el.put("filePath", file.getPath()); + el.put("parentCategoryId", parentid); + el.put("files",readFileRepository(file.toPath(),id+1, id+1, request)); + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) { + fileJSONArray.put(el); + }else{ + String filePath = file.getPath().toString(); + int startIndex = filePath.indexOf("repository") + 11; + filePath = filePath.substring(startIndex, filePath.length()); + if (scopes.contains(filePath)) { + fileJSONArray.put(el); + } + } + }else{ + JSONObject el = new JSONObject(); + String policyName = ""; + String version = ""; + String fileName = file.getName().toString(); + if(fileName.endsWith(".xml")){ + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + //Query the database + String parent = file.toString().substring(file.toString().indexOf("repository")+ 11); + parent = FilenameUtils.removeExtension(parent); + version = parent.substring(parent.indexOf(".")+1); + policyName = parent.substring(0, parent.lastIndexOf(".")); + if(policyName.contains("\\")){ + String scope = policyName.substring(0, policyName.lastIndexOf("\\")); + policyName = scope + "\\" + policyName.substring(policyName.lastIndexOf("\\")); + } + } + el.put("categoryId", id+1); + el.put("name", fileName); + el.put("parentCategoryId", parentid); + el.put("dateModified", lastModified(file)); + el.put("version", version); + el.put("filePath", file.getPath()); + el.put("files",new ArrayList()); + String query = "from PolicyVersion where POLICY_NAME ='" +policyName+"' and ACTIVE_VERSION ='"+version+"'"; + Boolean active = PolicyController.getActivePolicy(query); + if(active){ + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) { + fileJSONArray.put(el); + }else{ + String filePath = file.getPath().toString(); + int startIndex = filePath.indexOf("repository") + 11; + filePath = filePath.substring(startIndex, filePath.length()); + filePath = filePath.substring(0, filePath.lastIndexOf(File.separator)); + if (scopes.contains(filePath)) { + fileJSONArray.put(el); + } + } + } + } + } + } + return fileJSONArray; + } + + public Date lastModified(File file) { + return new Date(file.lastModified()); + } + + public String getVersion(File file) { + try { + return XACMLPolicyScanner.getVersion(Paths.get(file.getAbsolutePath())); + } catch (IOException e) { + return ""; + } + } + + public String getDomain(File file) { + String filePath = file.getAbsolutePath(); + int startIndex = filePath.indexOf("repository") + 11; + return filePath.substring(startIndex, filePath.length()); + } + + + @RequestMapping(value={"/auto_Push/PushPolicyToPDP.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView PushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + try { + ArrayList selectedPDPS = new ArrayList(); + ArrayList selectedPoliciesInUI = new ArrayList(); + this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups()); + ObjectMapper mapper = new ObjectMapper(); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + AutoPushTabAdapter adapter = (AutoPushTabAdapter) mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class); + for (Object pdpGroupId : adapter.getPdpDatas()) { + LinkedHashMap selectedPDP = (LinkedHashMap)pdpGroupId; + for(EcompPDPGroup pdpGroup : this.groups){ + if(pdpGroup.getId().equals(selectedPDP.get("id"))){ + selectedPDPS.add(pdpGroup); + } + } + } + + for (Object policyId : adapter.getPolicyDatas()) { + LinkedHashMap selected = (LinkedHashMap)policyId; + Path file = Paths.get(selected.get("filePath").toString()); + selectedPoliciesInUI.add(file.toFile()); + } + + for (Object pdpDestinationGroupId : selectedPDPS) { + Set currentPoliciesInGroup = new HashSet(); + Set selectedPolicies = new HashSet(); + for (File policyId : selectedPoliciesInUI) { + logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId); + // + // Get the current selection + File selectedItem = policyId; + // + assert (selectedItem != null); + if (selectedItem.isDirectory()) { + //AdminNotification.warn("Select only the Policy"); + return null; + } + // create the id of the target file + // Our standard for file naming is: + // ...xml + // since the file name usually has a ".xml", we need to strip + // that + // before adding the other parts + String name = selectedItem.getName(); + if(name.endsWith(".xml")){ + name = name.substring(0, name.length() - 4); + name = name.substring(0, name.lastIndexOf(".")); + } + String id = name; + if (id.endsWith(".xml")) { + id = id.substring(0, id.length() - 4); + id = id.substring(0, id.lastIndexOf(".")); + } + // add on the version string + String version = getVersion(selectedItem); + id += "." + version; + // put the .xml on the end + id += ".xml"; + // track on the domain in front. Do this one level at a time + // until we + // reach one of the roots + String domain = getDomain(selectedItem); + String mainDomain = domain.substring(0, domain.lastIndexOf(File.separator) ); + logger.info("print the main domain value"+mainDomain); + String path = mainDomain.replace('\\', '.'); + if(path.contains("/")){ + path = mainDomain.replace('/', '.'); + logger.info("print the path:" +path); + } + id = path + "." + id; + // Default policy to be Root policy; user can change to deferred + // later + URI selectedURI = selectedItem.toURI(); + StdPDPPolicy selectedPolicy = null; + try { + // + // Create the policy + selectedPolicy = new StdPDPPolicy(id, true, name, selectedURI); + } catch (IOException e) { + logger.error("Unable to create policy '" + id + "': "+ e.getMessage()); + //AdminNotification.warn("Unable to create policy '" + id + "': " + e.getMessage()); + } + StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId; + if (selectedPolicy != null) { + // Add Current policies from container + for (EcompPDPGroup group : container.getGroups()) { + if (group.getId().equals(selectedGroup.getId())) { + currentPoliciesInGroup.addAll(group.getPolicies()); + } + } + // copy policy to PAP + try { + PolicyController.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId); + } catch (PAPException e) { + e.printStackTrace(); + return null; + } + selectedPolicies.add(selectedPolicy); + } + } + StdPDPGroup pdpGroup = (StdPDPGroup) pdpDestinationGroupId; + StdPDPGroup updatedGroupObject = new StdPDPGroup(pdpGroup.getId(), pdpGroup.isDefaultGroup(), pdpGroup.getName(), pdpGroup.getDescription(), pdpGroup.getDirectory()); + updatedGroupObject.setEcompPdps(pdpGroup.getEcompPdps()); + updatedGroupObject.setPipConfigs(pdpGroup.getPipConfigs()); + updatedGroupObject.setStatus(pdpGroup.getStatus()); + + // replace the original set of Policies with the set from the + // container (possibly modified by the user) + // do not allow multiple copies of same policy + Iterator policyIterator = currentPoliciesInGroup.iterator(); + logger.debug("policyIterator....." + selectedPolicies); + while (policyIterator.hasNext()) { + PDPPolicy existingPolicy = policyIterator.next(); + for (PDPPolicy selPolicy : selectedPolicies) { + if (selPolicy.getName().equals(existingPolicy.getName())) { + if (selPolicy.getVersion().equals(existingPolicy.getVersion())) { + if (selPolicy.getId().equals(existingPolicy.getId())) { + policyIterator.remove(); + logger.debug("Removing policy: " + selPolicy); + break; + } + } else { + policyIterator.remove(); + logger.debug("Removing Old Policy version: "+ selPolicy); + break; + } + } + } + } + + currentPoliciesInGroup.addAll(selectedPolicies); + updatedGroupObject.setPolicies(currentPoliciesInGroup); + this.container.updateGroup(updatedGroupObject); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + return null; + } + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/auto_Push/remove_GroupPolicies.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + try { + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + StdPDPGroup group = (StdPDPGroup)mapper.readValue(root.get("activePdpGroup").toString(), StdPDPGroup.class); + JsonNode removePolicyData = root.get("data"); + policyContainer = new PDPPolicyContainer(group); + if(removePolicyData.size() > 0){ + for(int i = 0 ; i < removePolicyData.size(); i++){ + String data = removePolicyData.get(i).toString(); + AutoPushController.policyContainer.removeItem(data); + } + Set changedPolicies = new HashSet(); + changedPolicies.addAll((Collection) AutoPushController.policyContainer.getItemIds()); + StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null); + updatedGroupObject.setPolicies(changedPolicies); + updatedGroupObject.setEcompPdps(group.getEcompPdps()); + updatedGroupObject.setPipConfigs(group.getPipConfigs()); + updatedGroupObject.setStatus(group.getStatus()); + this.container.updateGroup(updatedGroupObject); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + + out.write(j.toString()); + + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + +} \ No newline at end of file diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java new file mode 100644 index 000000000..7a2b24e84 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java @@ -0,0 +1,723 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.dao.BRMSParamTemplateDao; +import org.openecomp.policy.rest.jpa.BRMSParamTemplate; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping("/") +public class CreateBRMSParamController extends RestrictedBaseController { + private static final Logger logger = FlexLogger.getLogger(CreateBRMSParamController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static BRMSParamTemplateDao bRMSParamTemplateDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateBRMSParamController(RuleAlgorithmsDao ruleAlgorithmsDao, BRMSParamTemplateDao bRMSParamTemplateDao, PolicyVersionDao policyVersionDao, + WatchPolicyNotificationDao policyNotificationDao){ + CreateBRMSParamController.policyVersionDao = policyVersionDao; + CreateBRMSParamController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateBRMSParamController.bRMSParamTemplateDao = bRMSParamTemplateDao; + CreateBRMSParamController.policyNotificationDao = policyNotificationDao; + } + + public CreateBRMSParamController(){} + protected PolicyAdapter policyAdapter = null; + private ArrayList attributeList; + private String ruleID = ""; + + private HashMap dynamicLayoutMap; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + dynamicLayoutMap = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String rule = findRule(root.get("policyData").toString().replaceAll("^\"|\"$", "")); + generateUI(rule); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(dynamicLayoutMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + + protected String findRule(String ruleTemplate) { + for (BRMSParamTemplate bRMSParamTemplate: bRMSParamTemplateDao.getBRMSParamTemplateData()){ + if(bRMSParamTemplate.getRuleName().equals(ruleTemplate)){ + return bRMSParamTemplate.getRule(); + } + } + return null; + } + + protected void generateUI(String rule) { + if(rule!=null){ + try { + String params = ""; + Boolean flag = false; + Boolean comment = false; + String lines[] = rule.split("\n"); + for(String line : lines){ + if (line.isEmpty() || line.startsWith("//")) { + continue; + } + if (line.startsWith("/*")) { + comment = true; + continue; + } + if (line.contains("//")) { + line = line.split("\\/\\/")[0]; + } + if (line.contains("/*")) { + comment = true; + if (line.contains("*/")) { + try { + comment = false; + line = line.split("\\/\\*")[0] + + line.split("\\*\\/")[1].replace("*/", ""); + } catch (Exception e) { + line = line.split("\\/\\*")[0]; + } + } else { + line = line.split("\\/\\*")[0]; + } + } + if (line.contains("*/")) { + comment = false; + try { + line = line.split("\\*\\/")[1].replace("*/", ""); + } catch (Exception e) { + line = ""; + } + } + if (comment) { + continue; + } + if (flag) { + params = params + line; + } + if (line.contains("declare Params")) { + params = params + line; + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = params.replace("declare Params", "").replace("end", "") + .replaceAll("\\s+", ""); + String[] components = params.split(":"); + String caption = ""; + for (int i = 0; i < components.length; i++) { + String type = ""; + if (i == 0) { + caption = components[i]; + } + if(caption.equals("")){ + break; + } + String nextComponent = ""; + try { + nextComponent = components[i + 1]; + } catch (Exception e) { + nextComponent = components[i]; + } + if (nextComponent.startsWith("String")) { + type = "String"; + createField(caption, type); + caption = nextComponent.replace("String", ""); + } else if (nextComponent.startsWith("int")) { + type = "int"; + createField(caption, type); + caption = nextComponent.replace("int", ""); + } + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + } + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + private void createField(String caption, String type) { + dynamicLayoutMap.put(caption, type); + } + + @RequestMapping(value={"/policyController/save_BRMSParamPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveBRMSParamPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_BRMS_Param_" + policyData.getPolicyName(); + List policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map successMap = new HashMap(); + Map attributeMap = new HashMap(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("key").toString(); + String value = ((LinkedHashMap) attribute).get("value").toString(); + attributeMap.put(key, value); + } + } + } + + policyData.setEcompName("DROOLS"); + policyData.setConfigName("BRMS_PARAM_RULE"); + policyData.setDynamicFieldConfigAttributes(attributeMap); + //convert drl rule and UI parameters into a map + Map drlRuleAndUIParams = new HashMap(); + // If there is any dynamic field create the matches here + String key="templateName"; + String value=(String) policyData.getRuleName(); + drlRuleAndUIParams.put(key, value); + System.out.println(policyData.getRuleData()); + if(policyData.getRuleData().size() > 0){ + for(Object keyValue: policyData.getRuleData().keySet()){ + drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString()); + } + } + policyData.setBRMSParamBody(drlRuleAndUIParams); + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + public void PrePopulateBRMSParamPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList(); + dynamicLayoutMap = new HashMap(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // policy name value is the policy name without any prefix and + // Extensions. + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Param_") +11, policyAdapter.getPolicyName().lastIndexOf(".")); + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Set Attributes. + AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); + for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ + for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ + if(attributeAssignment.getAttributeId().startsWith("key:")){ + Map attribute = new HashMap(); + String key = attributeAssignment.getAttributeId().replace("key:", ""); + attribute.put("key", key); + JAXBElement attributevalue = (JAXBElement) attributeAssignment.getExpression(); + String value = (String) attributevalue.getValue().getContent().get(0); + attribute.put("value", value); + attributeList.add(attribute); + } + } + policyAdapter.setAttributes(attributeList); + } + String ruleConfigName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + ".txt"; + policyAdapter.setConfigBodyPath(ruleConfigName); + paramUIGenerate(policyAdapter); + // Get the target data under policy. + policyAdapter.setDynamicLayoutMap(dynamicLayoutMap); + if(policyAdapter.getDynamicLayoutMap().size() > 0){ + LinkedHashMap drlRule = new LinkedHashMap(); + for(Object keyValue: policyAdapter.getDynamicLayoutMap().keySet()){ + drlRule.put(keyValue.toString(), policyAdapter.getDynamicLayoutMap().get(keyValue).toString()); + } + policyAdapter.setRuleData(drlRule); + } + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + if (index == 3){ + policyAdapter.setRiskType(value); + } + + if (index == 4){ + policyAdapter.setRiskLevel(value); + } + + if (index == 5){ + policyAdapter.setGuard(value); + } + if (index == 6 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + + index++; + } + } + } + } + } + } + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + // This method generates the UI from rule configuration + private void paramUIGenerate(PolicyAdapter policyAdapter) { + String fileLocation = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null) { + fileLocation = PolicyController.getConfigHome(); + } + if (logger.isDebugEnabled()) { + logger.debug("Attempting to read file from the location: " + fileLocation); + } + if (fileLocation == null) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Error with the FileName: " + fileName); + return; + } + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName) + && file.toString().endsWith(".txt")) { + // Reading the file + try { + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage()); + } + String params = ""; + Boolean flag = false; + Boolean comment = false; + for (String line : Files.readAllLines(Paths.get(file.toString()))) { + if (line.isEmpty() || line.startsWith("//")) { + continue; + } + if(line.contains("<$%BRMSParamTemplate=")){ + String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>")); + value = value.replace("<$%BRMSParamTemplate=", ""); + policyAdapter.setRuleName(value); + } + if (line.startsWith("/*")) { + comment = true; + continue; + } + if (line.contains("//")) { + if(!(line.contains("http://") || line.contains("https://"))){ + line = line.split("\\/\\/")[0]; + } + } + if (line.contains("/*")) { + comment = true; + if (line.contains("*/")) { + try { + comment = false; + line = line.split("\\/\\*")[0] + + line.split("\\*\\/")[1].replace( + "*/", ""); + } catch (Exception e) { + line = line.split("\\/\\*")[0]; + } + } else { + line = line.split("\\/\\*")[0]; + } + } + if (line.contains("*/")) { + comment = false; + try { + line = line.split("\\*\\/")[1] + .replace("*/", ""); + } catch (Exception e) { + line = ""; + } + } + if (comment) { + continue; + } + if (flag) { + params = params + line; + } + if (line.contains("rule \"Params\"")) { + params = params + line; + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = params.replaceAll("\\s+", "").replace("rule\"Params\"salience1000whenthenParamsparams=newParams();","") + .replace("insert(params);end", "") + .replace("params.set", ""); + String[] components = params.split(";"); + if(components!= null && components.length > 0){ + for (int i = 0; i < components.length; i++) { + String value = null; + String caption = components[i].substring(0, + components[i].indexOf("(")); + caption = caption.substring(0, 1).toLowerCase() + caption.substring(1); + if (components[i].contains("(\"")) { + value = components[i] + .substring(components[i].indexOf("(\""), + components[i].indexOf("\")")) + .replace("(\"", "").replace("\")", ""); + } else { + value = components[i] + .substring(components[i].indexOf("("), + components[i].indexOf(")")) + .replace("(", "").replace(")", ""); + } + dynamicLayoutMap.put(caption, value); + + } + } + } catch (FileNotFoundException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); + } catch (IOException e1) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e1.getMessage()); + } + } + } + } + + // set View Rule + @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView setViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + + String body = ""; + + body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " + + "<$%BRMSParamTemplate=" + policyData.getRuleName() + "%$> \n */ \n"; + body = body + findRule((String) policyData.getRuleName()) + "\n"; + String generatedRule = "rule \"Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();"; + + if(policyData.getRuleData().size() > 0){ + for(Object keyValue: policyData.getRuleData().keySet()){ + String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1); + if (keyValue.equals("String")) { + generatedRule = generatedRule + "\n\t\tparams.set" + + key + "(\"" + + policyData.getRuleData().get(keyValue).toString() + "\");"; + } else { + generatedRule = generatedRule + "\n\t\tparams.set" + + key + "(" + + policyData.getRuleData().get(keyValue).toString() + ");"; + } + } + } + generatedRule = generatedRule + + "\n\t\tinsert(params);\nend"; + logger.info("New rule generated with :" + generatedRule); + body = body + generatedRule; + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(body); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + return null; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java new file mode 100644 index 000000000..6dcd8400b --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java @@ -0,0 +1,440 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping("/") +public class CreateBRMSRawController extends RestrictedBaseController { + + private static final Logger logger = FlexLogger.getLogger(CreateBRMSRawController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateBRMSRawController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){ + CreateBRMSRawController.policyVersionDao = policyVersionDao; + CreateBRMSRawController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateBRMSRawController.policyNotificationDao = policyNotificationDao; + } + + public CreateBRMSRawController(){} + protected PolicyAdapter policyAdapter = null; + private ArrayList attributeList; + private String ruleID = ""; + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + + + @RequestMapping(value={"/policyController/save_BRMSRawPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveBRMSRawPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_BRMS_Raw_" + policyData.getPolicyName(); + List policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map successMap = new HashMap(); + Map attributeMap = new HashMap(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("key").toString(); + String value = ((LinkedHashMap) attribute).get("value").toString(); + attributeMap.put(key, value); + } + } + } + + + policyData.setEcompName("DROOLS"); + policyData.setConfigName("BRMS_RAW_RULE"); + policyData.setDynamicFieldConfigAttributes(attributeMap); + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + public void PrePopulateBRMSRawPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + PolicyType policy = (PolicyType) policyAdapter.getPolicyData(); + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + // policy name value is the policy name without any prefix and + // Extensions. + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("BRMS_Raw_") +9, policyAdapter.getPolicyName().lastIndexOf(".")); + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating form data for BRMS RAW Policy selected:" + policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Set Attributes. + AdviceExpressionsType expressionTypes = ((RuleType)policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().get(0)).getAdviceExpressions(); + for( AdviceExpressionType adviceExpression: expressionTypes.getAdviceExpression()){ + for(AttributeAssignmentExpressionType attributeAssignment: adviceExpression.getAttributeAssignmentExpression()){ + if(attributeAssignment.getAttributeId().startsWith("key:")){ + Map attribute = new HashMap(); + String key = attributeAssignment.getAttributeId().replace("key:", ""); + attribute.put("key", key); + JAXBElement attributevalue = (JAXBElement) attributeAssignment.getExpression(); + String value = (String) attributevalue.getValue().getContent().get(0); + attribute.put("value", value); + attributeList.add(attribute); + } + } + policyAdapter.setAttributes(attributeList); + } + String ruleConfigName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + "."; + policyAdapter.setConfigBodyPath(ruleConfigName); + // Get the target data under policy. + policyAdapter.setConfigBodyData(readFile(policyAdapter)); + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + if (index == 3){ + policyAdapter.setRiskType(value); + } + + if (index == 4){ + policyAdapter.setRiskLevel(value); + } + + if (index == 5){ + policyAdapter.setGuard(value); + } + if (index == 6 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + + index++; + } + } + } + } + } + } + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + // Here we are reading the configurations file + protected String readFile(PolicyAdapter policyAdapter) { + String fileLocation = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null ) { + fileLocation = PolicyController.getConfigHome(); + } + if (fileLocation == null) { + return fileLocation; + } + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName) && file.toString().endsWith(".txt")) { + // Reading the file + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + return sb.toString(); + } catch (FileNotFoundException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); + } catch (IOException e1) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e1.getMessage()); + } + } + } + return null; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java new file mode 100644 index 000000000..b41f7e0ef --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java @@ -0,0 +1,889 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.ClosedLoopFaultBody; +import org.openecomp.policy.adapter.ClosedLoopFaultTriggerUISignatures; +import org.openecomp.policy.adapter.ClosedLoopSignatures; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.dao.VarbindDictionaryDao; +import org.openecomp.policy.rest.jpa.EcompName; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.policy.rest.jpa.VarbindDictionary; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateClosedLoopFaultController extends RestrictedBaseController{ + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static VarbindDictionaryDao varbindDictionaryDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateClosedLoopFaultController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, VarbindDictionaryDao varbindDictionaryDao, + WatchPolicyNotificationDao policyNotificationDao){ + CreateClosedLoopFaultController.policyVersionDao = policyVersionDao; + CreateClosedLoopFaultController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateClosedLoopFaultController.varbindDictionaryDao = varbindDictionaryDao; + CreateClosedLoopFaultController.policyNotificationDao = policyNotificationDao; + } + + public CreateClosedLoopFaultController(){} + protected PolicyAdapter policyAdapter = null; + private String ruleID = ""; + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/policyController/save_Faultpolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveFaultPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + TrapDatas trapDatas = mapper.readValue(root.get("trapData").toString(), TrapDatas.class); + TrapDatas faultDatas = mapper.readValue(root.get("faultData").toString(), TrapDatas.class); + ClosedLoopGridJSONData policyJsonData = mapper.readValue(root.get("policyData").get("policy").toString(), ClosedLoopGridJSONData.class); + ClosedLoopFaultBody jsonBody = mapper.readValue(root.get("policyData").get("policy").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + ArrayList trapSignatureDatas = new ArrayList(); + if(trapDatas.getTrap1() != null){ + trapSignatureDatas.add(trapDatas); + } + ArrayList faultSignatureDatas = new ArrayList(); + if(faultDatas.getTrap1() != null){ + faultSignatureDatas.add(faultDatas); + } + + String resultBody = ""; + if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){ + resultBody = resultBody + "("; + for(int i = policyJsonData.getConnecttriggerSignatures().size()-1; i>=0 ; i--){ + String connectBody = connectTriggerSignature(i, policyJsonData.getConnecttriggerSignatures(), trapSignatureDatas.get(0)); + resultBody = resultBody + connectBody; + } + resultBody = resultBody + ")"; + }else{ + if(!trapSignatureDatas.isEmpty()){ + resultBody = callTrap("nill", trapSignatureDatas.get(0)); + } + } + ClosedLoopSignatures triggerSignatures = new ClosedLoopSignatures(); + triggerSignatures.setSignatures(resultBody); + if(policyData.getClearTimeOut() != null){ + triggerSignatures.setTimeWindow(Integer.parseInt(policyData.getClearTimeOut())); + triggerSignatures.setTrapMaxAge(Integer.parseInt(policyData.getTrapMaxAge())); + ClosedLoopFaultTriggerUISignatures uiTriggerSignatures = new ClosedLoopFaultTriggerUISignatures(); + if(!trapSignatureDatas.isEmpty()){ + uiTriggerSignatures.setSignatures(getUITriggerSignature("Trap", trapSignatureDatas.get(0))); + if(!policyJsonData.getConnecttriggerSignatures().isEmpty()){ + uiTriggerSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnecttriggerSignatures())); + } + } + jsonBody.setTriggerSignaturesUsedForUI(uiTriggerSignatures); + jsonBody.setTriggerTimeWindowUsedForUI(Integer.parseInt(policyData.getClearTimeOut())); + jsonBody.setTrapMaxAgeUsedForUI(Integer.parseInt(policyData.getTrapMaxAge())); + } + + jsonBody.setTriggerSignatures(triggerSignatures); + String faultBody = ""; + if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){ + faultBody = faultBody + "("; + for(int i = policyJsonData.getConnectVerificationSignatures().size()-1; i>=0 ; i--){ + String connectBody = connectTriggerSignature(i, policyJsonData.getConnectVerificationSignatures(), faultSignatureDatas.get(0)); + faultBody = faultBody + connectBody; + } + faultBody = faultBody + ")"; + }else{ + if(!faultSignatureDatas.isEmpty()){ + faultBody = callTrap("nill", faultSignatureDatas.get(0)); + } + } + ClosedLoopSignatures faultSignatures = new ClosedLoopSignatures(); + faultSignatures.setSignatures(faultBody); + if(policyData.getVerificationclearTimeOut() != null){ + faultSignatures.setTimeWindow(Integer.parseInt(policyData.getVerificationclearTimeOut())); + ClosedLoopFaultTriggerUISignatures uifaultSignatures = new ClosedLoopFaultTriggerUISignatures(); + if(!faultSignatureDatas.isEmpty()){ + uifaultSignatures.setSignatures(getUITriggerSignature("Fault", faultSignatureDatas.get(0))); + if(!policyJsonData.getConnectVerificationSignatures().isEmpty()){ + uifaultSignatures.setConnectSignatures(getUIConnectTraps(policyJsonData.getConnectVerificationSignatures())); + } + } + + jsonBody.setVerificationSignaturesUsedForUI(uifaultSignatures); + jsonBody.setVerfificationTimeWindowUsedForUI(Integer.parseInt(policyData.getVerificationclearTimeOut())); + } + jsonBody.setVerificationSignatures(faultSignatures); + ObjectWriter om = new ObjectMapper().writer(); + String json = om.writeValueAsString(jsonBody); + policyData.setJsonBody(json); + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_Fault_" + policyData.getPolicyName(); + List policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map successMap = new HashMap(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List ruleAlgorithsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List versionlist = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionlist.size() > 0) { + for(int i = 0; i < versionlist.size(); i++) { + PolicyVersion entityItem = versionlist.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + //connect traps data set to JSON Body as String + @SuppressWarnings("rawtypes") + private String getUIConnectTraps(ArrayList connectTrapSignatures) { + String resultBody = ""; + String connectMainBody = ""; + for(int j = 0; j < connectTrapSignatures.size(); j++){ + Map connectTraps = (Map)connectTrapSignatures.get(j); + String connectBody = ""; + Object object = connectTraps; + if(object instanceof LinkedHashMap){ + String notBox = ""; + if(((LinkedHashMap) object).keySet().contains("notBox")){ + notBox = ((LinkedHashMap) object).get("notBox").toString(); + } + String connectTrap1 = ((LinkedHashMap) object).get("connectTrap1").toString(); + String trapCount1 = ((LinkedHashMap) object).get("trapCount1").toString(); + String operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); + String connectTrap2 = ((LinkedHashMap) object).get("connectTrap2").toString(); + String trapCount2 = ((LinkedHashMap) object).get("trapCount2").toString(); + connectBody = notBox + "@!" + connectTrap1 + "@!" + trapCount1 + "@!" + operatorBox + "@!" + connectTrap2 + "@!" + trapCount2 + "#!?!"; + } + resultBody = resultBody + connectBody; + } + connectMainBody = connectMainBody + resultBody; + return connectMainBody; + } + + + + // get Trigger signature from JSON body + private String getUITriggerSignature(String trap, Object object2) { + String triggerBody = ""; + TrapDatas trapDatas = (TrapDatas) object2; + ArrayList attributeList = new ArrayList<>(); + // Read the Trap + if(trap.startsWith("Trap")){ + if(trapDatas.getTrap1()!= null){ + attributeList.add(trapDatas.getTrap1()); + } + if(trapDatas.getTrap2()!= null){ + attributeList.add(trapDatas.getTrap2()); + } + if(trapDatas.getTrap3()!= null){ + attributeList.add(trapDatas.getTrap3()); + } + if(trapDatas.getTrap4()!= null){ + attributeList.add(trapDatas.getTrap4()); + } + if(trapDatas.getTrap5()!= null){ + attributeList.add(trapDatas.getTrap5()); + } + if(trapDatas.getTrap6()!= null){ + attributeList.add(trapDatas.getTrap6()); + } + }else{ + if(trap.equals("Fault")){ + if(trapDatas.getTrap1()!= null){ + attributeList.add(trapDatas.getTrap1()); + } + if(trapDatas.getTrap2()!= null){ + attributeList.add(trapDatas.getTrap2()); + } + if(trapDatas.getTrap3()!= null){ + attributeList.add(trapDatas.getTrap3()); + } + if(trapDatas.getTrap4()!= null){ + attributeList.add(trapDatas.getTrap4()); + } + if(trapDatas.getTrap5()!= null){ + attributeList.add(trapDatas.getTrap5()); + } + if(trapDatas.getTrap6()!= null){ + attributeList.add(trapDatas.getTrap6()); + } + } + } + + for(int j = 0; j < attributeList.size(); j++){ + String signatureBody = ""; + ArrayList connectTraps = (ArrayList) attributeList.get(j); + for(int i =0 ; i < connectTraps.size(); i++){ + String connectBody = ""; + Object object = connectTraps.get(i); + if(object instanceof LinkedHashMap){ + String notBox = ""; + if(((LinkedHashMap) object).keySet().contains("notBox")){ + notBox = ((LinkedHashMap) object).get("notBox").toString(); + } + String trigger1 = ((LinkedHashMap) object).get("trigger1").toString(); + String operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); + String trigger2 = ((LinkedHashMap) object).get("trigger2").toString(); + connectBody = notBox + "@!" + trigger1 + "@!" + operatorBox + "@!" + trigger2 + "#!"; + } + signatureBody = signatureBody + connectBody; + } + triggerBody = triggerBody + signatureBody + "?!"; + } + + return triggerBody; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + private String callTrap(String trap, Object object) { + String signatureBody = ""; + TrapDatas trapDatas = (TrapDatas) object; + ArrayList attributeList = new ArrayList<>(); + // Read the Trap + if(!trap.equals("nill")){ + try{ + if(trap.startsWith("Trap")){ + if(trap.equals("Trap1")){ + attributeList = trapDatas.getTrap1(); + }else if(trap.equals("Trap2")){ + attributeList = trapDatas.getTrap2(); + }else if(trap.equals("Trap3")){ + attributeList = trapDatas.getTrap3(); + }else if(trap.equals("Trap4")){ + attributeList = trapDatas.getTrap4(); + }else if(trap.equals("Trap5")){ + attributeList = trapDatas.getTrap5(); + }else if(trap.equals("Trap6")){ + attributeList = trapDatas.getTrap6(); + } + }else{ + if(trap.equals("Fault")){ + if(trap.equals("Fault1")){ + attributeList = trapDatas.getTrap1(); + }else if(trap.equals("Fault2")){ + attributeList = trapDatas.getTrap2(); + }else if(trap.equals("Fault3")){ + attributeList = trapDatas.getTrap3(); + }else if(trap.equals("Fault4")){ + attributeList = trapDatas.getTrap4(); + }else if(trap.equals("Fault5")){ + attributeList = trapDatas.getTrap5(); + }else if(trap.equals("Fault6")){ + attributeList = trapDatas.getTrap6(); + } + } + } + } catch(Exception e){ + return "(" + trap + ")"; + } + }else{ + if(trapDatas.getTrap1()!=null){ + attributeList = trapDatas.getTrap1(); + }else{ + return ""; + } + } + signatureBody = signatureBody + "(" + readAttributes(attributeList, attributeList.size()-1) + ")"; + return signatureBody; + } + + private String readAttributes(ArrayList object, int index) { + String attributes = ""; + Map trapSignatures = (Map) object.get(index); + // Read the Elements. + Object notBox = ""; + if(trapSignatures.keySet().contains("notBox")){ + notBox = trapSignatures.get("notBox"); + } + if(notBox!=null){ + attributes = attributes + notBox.toString(); + } + Object trapName1 = trapSignatures.get("trigger1"); + if(trapName1!=null){ + String attrib = trapName1.toString(); + if(attrib.startsWith("A")){ + try{ + int iy = Integer.parseInt(attrib.substring(1))-1; + attributes = attributes + "(" + readAttributes(object, iy) + ")"; + }catch(NumberFormatException e){ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; + } catch (UnsupportedEncodingException e1) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); + } + } + }else{ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8")+ ")"; + } catch (UnsupportedEncodingException e) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); + } + } + }else{ + return ""; + } + Object comboBox = trapSignatures.get("operatorBox"); + if(comboBox!=null){ + attributes = attributes + comboBox.toString(); + }else{ + return attributes; + } + Object trapName2 = trapSignatures.get("trigger2"); + if(trapName2!=null){ + String attrib = trapName2.toString(); + if(attrib.startsWith("A")){ + try{ + int iy = Integer.parseInt(attrib.substring(1))-1; + attributes = attributes + "(" + readAttributes(object, iy) + ")"; + }catch(NumberFormatException e){ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; + } catch (UnsupportedEncodingException e1) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e1); + } + } + }else{ + try { + attrib = getVarbindOID(attrib); + attributes = attributes + "("+ URLEncoder.encode(attrib, "UTF-8") + ")"; + } catch (UnsupportedEncodingException e) { + //logger.error("Caused Exception while Encoding Varbind Dictionary Values"+e); + } + } + } + return attributes; + } + + private String getVarbindOID(String attrib) { + VarbindDictionary varbindId = varbindDictionaryDao.getVarbindEntityByName(attrib).get(0); + return varbindId.getVarbindOID(); + } + + private String connectTriggerSignature(int index, ArrayList triggerSignatures, Object object) { + String resultBody = ""; + Map connectTraps = (Map) triggerSignatures.get(index); + try{ + String notBox = ""; + if(connectTraps.keySet().contains("notBox")){ + notBox = connectTraps.get("notBox"); + } + resultBody = resultBody + "(" + notBox; + }catch(NullPointerException e){ + resultBody = resultBody + "("; + } + String connectTrap1 = connectTraps.get("connectTrap1"); + if(connectTrap1.startsWith("Trap") || connectTrap1.startsWith("Fault")){ + String trapBody = callTrap(connectTrap1, object); + if(trapBody!=null){ + resultBody = resultBody + trapBody; + } + }else if(connectTrap1.startsWith("C")){ + for(int i=0; i<= triggerSignatures.size(); i++){ + Map triggerSignature = (Map) triggerSignatures.get(i); + if(triggerSignature.get("id").equals(connectTrap1)){ + resultBody = resultBody + "("; + String connectBody = connectTriggerSignature(i, triggerSignatures, object); + resultBody = resultBody + connectBody + ")"; + }else{ + i++; + } + } + } + try{ + String trapCount1 = connectTraps.get("trapCount1"); + resultBody = resultBody + ", Time = " + trapCount1 + ")"; + }catch(NullPointerException e){ + } + try{ + String operatorBox = connectTraps.get("operatorBox"); + resultBody = resultBody + operatorBox +"("; + }catch (NullPointerException e){ + } + try{ + String connectTrap2 = connectTraps.get("connectTrap2"); + if(connectTrap2.startsWith("Trap") || connectTrap2.startsWith("Fault")){ + String trapBody = callTrap(connectTrap2, object); + if(trapBody!=null){ + resultBody = resultBody + trapBody; + } + }else if(connectTrap2.startsWith("C")){ + for(int i=0; i<= triggerSignatures.size(); i++){ + Map triggerSignature = (Map) triggerSignatures.get(i); + if(triggerSignature.get("id").equals(connectTrap2)){ + resultBody = resultBody + "("; + String connectBody = connectTriggerSignature(i, triggerSignatures, object); + resultBody = resultBody + connectBody + ")"; + }else{ + i++; + } + } + } + }catch(NullPointerException e){ + } + try{ + String trapCount2 = connectTraps.get("trapCount2"); + resultBody = resultBody + ", Time = " + trapCount2 + ")"; + }catch(NullPointerException e){ + } + return resultBody; + } + + public void PrePopulateClosedLoopFaultPolicyData(PolicyAdapter policyAdapter) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("Fault_") +6 , policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + // First match in the target is EcompName, so set that value. + if (index == 1) { + policyAdapter.setEcompName(value); + EcompName ecompName = new EcompName(); + ecompName.setEcompName(value); + policyAdapter.setEcompNameField(ecompName); + } + if (index == 2){ + policyAdapter.setRiskType(value); + } + + if (index == 3){ + policyAdapter.setRiskLevel(value); + } + + if (index == 4){ + policyAdapter.setGuard(value); + } + if (index == 5 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + index++; + } + } + } + } + } + } + } + String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + "."; + policyAdapter.setConfigBodyPath(jsonBodyName); + readClosedLoopJSONFile(policyAdapter); + } + + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + private String readClosedLoopJSONFile(PolicyAdapter policyAdapter) { + String fileLocation = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null ) { + fileLocation = PolicyController.getConfigHome(); + } + if (fileLocation == null) { + return fileLocation; + } + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName)) { + FileInputStream inputStream = null; + String location = file.toString(); + try { + inputStream = new FileInputStream(location); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + if (location.endsWith("json")) { + JsonReader jsonReader = null; + jsonReader = Json.createReader(inputStream); + ObjectMapper mapper = new ObjectMapper(); + try { + ClosedLoopFaultBody closedLoopBody = mapper.readValue(jsonReader.read().toString(), ClosedLoopFaultBody.class); + if(closedLoopBody.getClosedLoopPolicyStatus().equalsIgnoreCase("ACTIVE")){ + closedLoopBody.setClosedLoopPolicyStatus("Active"); + }else{ + closedLoopBody.setClosedLoopPolicyStatus("InActive"); + } + policyAdapter.setJsonBodyData(closedLoopBody); + if(closedLoopBody.getTrapMaxAgeUsedForUI() != null){ + policyAdapter.setTrapMaxAge(closedLoopBody.getTrapMaxAgeUsedForUI().toString()); + } + if(closedLoopBody.getTriggerTimeWindowUsedForUI() != null){ + policyAdapter.setClearTimeOut(closedLoopBody.getTriggerTimeWindowUsedForUI().toString()); + } + if(closedLoopBody.getVerfificationTimeWindowUsedForUI() != null){ + policyAdapter.setVerificationclearTimeOut(closedLoopBody.getVerfificationTimeWindowUsedForUI().toString()); + } + + } catch (Exception e) { + e.printStackTrace(); + } + jsonReader.close(); + } + } + } + return null; + } + +} + +class ClosedLoopGridJSONData{ + + private String clearTimeOut; + private String trapMaxAge; + private String verificationclearTimeOut; + private ArrayList connecttriggerSignatures; + private ArrayList connectVerificationSignatures; + + public String getClearTimeOut() { + return clearTimeOut; + } + public void setClearTimeOut(String clearTimeOut) { + this.clearTimeOut = clearTimeOut; + } + public String getTrapMaxAge() { + return trapMaxAge; + } + public void setTrapMaxAge(String trapMaxAge) { + this.trapMaxAge = trapMaxAge; + } + public String getVerificationclearTimeOut() { + return verificationclearTimeOut; + } + public void setVerificationclearTimeOut(String verificationclearTimeOut) { + this.verificationclearTimeOut = verificationclearTimeOut; + } + + + public ArrayList getConnecttriggerSignatures() { + return connecttriggerSignatures; + } + public void setConnecttriggerSignatures(ArrayList connecttriggerSignatures) { + this.connecttriggerSignatures = connecttriggerSignatures; + } + public ArrayList getConnectVerificationSignatures() { + return connectVerificationSignatures; + } + public void setConnectVerificationSignatures(ArrayList connectVerificationSignatures) { + this.connectVerificationSignatures = connectVerificationSignatures; + } +} + +class TrapDatas{ + private ArrayList trap1; + private ArrayList trap2; + private ArrayList trap3; + private ArrayList trap4; + private ArrayList trap5; + private ArrayList trap6; + public ArrayList getTrap1() { + return trap1; + } + public void setTrap1(ArrayList trap1) { + this.trap1 = trap1; + } + public ArrayList getTrap2() { + return trap2; + } + public void setTrap2(ArrayList trap2) { + this.trap2 = trap2; + } + public ArrayList getTrap3() { + return trap3; + } + public void setTrap3(ArrayList trap3) { + this.trap3 = trap3; + } + public ArrayList getTrap4() { + return trap4; + } + public void setTrap4(ArrayList trap4) { + this.trap4 = trap4; + } + public ArrayList getTrap5() { + return trap5; + } + public void setTrap5(ArrayList trap5) { + this.trap5 = trap5; + } + public ArrayList getTrap6() { + return trap6; + } + public void setTrap6(ArrayList trap6) { + this.trap6 = trap6; + } +} \ No newline at end of file diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java new file mode 100644 index 000000000..f5e0557f8 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java @@ -0,0 +1,422 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.ClosedLoopPMBody; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateClosedLoopPMController extends RestrictedBaseController{ + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateClosedLoopPMController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){ + CreateClosedLoopPMController.policyVersionDao = policyVersionDao; + CreateClosedLoopPMController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateClosedLoopPMController.policyNotificationDao = policyNotificationDao; + } + + public CreateClosedLoopPMController(){} + + protected PolicyAdapter policyAdapter = null; + private String ruleID = ""; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/policyController/save_PMPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePMPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_PM_" + policyData.getPolicyName(); + List policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + + + if(policyData.getServiceTypePolicyName() != null){ + policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); + } + + ObjectMapper jsonMapper = new ObjectMapper(); + String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData()); + jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); + jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType()); + policyData.setJsonBody(jsonBody); + + Map successMap = new HashMap(); + + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + public void PrePopulateClosedLoopPMPolicyData(PolicyAdapter policyAdapter) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("PM_") +3 , policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + int index = 0; + Iterator iterMatch = matchList.iterator(); + while (matchList.size()>1 && iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + // First match in the target is EcompName, so set that value. + if (index == 0) { + policyAdapter.setEcompName(value); + } + + if (index == 1){ + policyAdapter.setRiskType(value); + } + + if (index == 2){ + policyAdapter.setRiskLevel(value); + } + + if (index == 3){ + policyAdapter.setGuard(value); + } + + if (index == 4 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + if (index == 5){ + LinkedHashMap serviceTypePolicyName1 = new LinkedHashMap<>(); + String key = "serviceTypePolicyName"; + serviceTypePolicyName1.put(key, value); + policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1); + } + index++; + } + } + } + } + } + } + } + String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+"."+ policyAdapter.getOldPolicyFileName() + "."; + policyAdapter.setConfigBodyPath(jsonBodyName); + readClosedLoopJSONFile(policyAdapter); + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + protected String readClosedLoopJSONFile(PolicyAdapter policyAdapter) { + String fileLocation = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null ) { + fileLocation = PolicyController.getConfigHome(); + } + if (fileLocation == null) { + return fileLocation; + } + + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName)) { + FileInputStream inputStream = null; + String location = file.toString(); + try { + inputStream = new FileInputStream(location); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + if (location.endsWith("json")) { + JsonReader jsonReader = null; + jsonReader = Json.createReader(inputStream); + ObjectMapper mapper = new ObjectMapper(); + try { + ClosedLoopPMBody closedLoopBody = mapper.readValue(jsonReader.read().toString(), ClosedLoopPMBody.class); + policyAdapter.setJsonBodyData(closedLoopBody); + } catch (IOException e) { + e.printStackTrace(); + /*logger.error("JSON Body Mapping Error");*/ + } + jsonReader.close(); + } + } + } + return null; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java new file mode 100644 index 000000000..c4d4cfd50 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java @@ -0,0 +1,987 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.Map.Entry; +import java.util.Properties; +import java.util.TreeMap; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RemoteCatalogValuesDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.dao.GroupPolicyScopeListDao; +import org.openecomp.policy.rest.dao.MicroServiceModelsDao; +import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; +import org.openecomp.policy.rest.jpa.MicroServiceModels; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RemoteCatalogValues; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.policy.utils.ConfigurableRESTUtils; +import org.openecomp.policy.utils.ConfigurableRESTUtils.RESQUEST_METHOD; +import org.openecomp.policy.utils.ConfigurableRESTUtils.REST_RESPONSE_FORMAT; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.fasterxml.jackson.databind.node.JsonNodeFactory; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.base.Joiner; +import com.google.common.base.Splitter; +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParser; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping("/") +public class CreateDcaeMicroServiceController extends RestrictedBaseController { + private static final Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static RemoteCatalogValuesDao remoteCatalogValuesDao; + private static MicroServiceModelsDao microServiceModelsDao; + private static PolicyVersionDao policyVersionDao; + private static GroupPolicyScopeListDao groupPolicyScopeListDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreateDcaeMicroServiceController(RuleAlgorithmsDao ruleAlgorithmsDao, RemoteCatalogValuesDao remoteCatalogValuesDao, + MicroServiceModelsDao microServiceModelsDao, PolicyVersionDao policyVersionDao, GroupPolicyScopeListDao groupPolicyScopeListDao, + WatchPolicyNotificationDao policyNotificationDao){ + CreateDcaeMicroServiceController.groupPolicyScopeListDao = groupPolicyScopeListDao; + CreateDcaeMicroServiceController.policyVersionDao = policyVersionDao; + CreateDcaeMicroServiceController.microServiceModelsDao = microServiceModelsDao; + CreateDcaeMicroServiceController.remoteCatalogValuesDao = remoteCatalogValuesDao; + CreateDcaeMicroServiceController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateDcaeMicroServiceController.policyNotificationDao = policyNotificationDao; + } + + public CreateDcaeMicroServiceController(){} + + protected PolicyAdapter policyAdapter = null; + private String ruleID = ""; + private int priorityCount; + private Map attributesListRefMap = new HashMap(); + private Map> arrayTextList = new HashMap>(); + + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + + @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); + String servicename = value.toString().split("-v")[0]; + String version = null; + if (value.toString().contains("-v")){ + version = value.toString().split("-v")[1]; + } + MicroServiceModels returnModel = getAttributeObject(servicename, version); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + List list = new ArrayList<>(); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(returnModel); + JSONObject j = new JSONObject("{dcaeModelData: " + responseString +"}"); + list.add(j); + out.write(list.toString()); + return null; + } + + private MicroServiceModels getAttributeObject(String name, String version) { + MicroServiceModels workingModel = new MicroServiceModels(); + List microServiceModelsData = microServiceModelsDao.getMicroServiceModelsData(); + for (int i = 0; i < microServiceModelsData.size(); i++) { + workingModel = microServiceModelsData.get(i); + if (version!=null && workingModel.getVersion()!=null){ + if (workingModel.getModelName().equals(name) && workingModel.getVersion().equals(version)){ + break; + } + }else{ + if (workingModel.getModelName().equals(name) && workingModel.getVersion() == null){ + break; + } + } + } + return workingModel; + } + + @RequestMapping(value={"/get_DCAEPriorityValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getDCAEPriorityValuesData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + List priorityList = new ArrayList(); + priorityCount = 10; + for (int i = 1; i < priorityCount; i++) { + priorityList.add(String.valueOf(i)); + } + model.put("priorityDatas", mapper.writeValueAsString(priorityList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + + @RequestMapping(value={"/policyController/save_DCAEMSPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveDCAEMSPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String jsonContent = null; + try{ + jsonContent = decodeContent(root.get("policyJSON")).toString(); + }catch(Exception e){ + logger.error("Error while decoding microservice content"); + } + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + if(policyData.isEditPolicy){ + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(dirName + root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_MS_" + policyData.getPolicyName(); + List versionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + policyData.setEcompName(policyData.getEcompName()); + //get the jsonBody + String jsonBody = null; + try { + jsonBody = constructJson(policyData, jsonContent); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + policyData.setJsonBody(jsonBody); + Map successMap = new HashMap(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List policyVersionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + + System.out.println(root); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + private JSONObject decodeContent(JsonNode jsonNode){ + Iterator jsonElements = jsonNode.elements(); + Iterator jsonKeys = jsonNode.fieldNames(); + Map element = new TreeMap(); + while(jsonElements.hasNext() && jsonKeys.hasNext()){ + element.put(jsonKeys.next(), jsonElements.next().toString()); + } + JSONObject jsonResult = new JSONObject(); + JSONArray jsonArray = null; + String oldValue = null; + String nodeKey = null; + String arryKey = null; + Boolean isArray = false; + JsonNodeFactory nodeFactory = JsonNodeFactory.instance; + ObjectNode node = nodeFactory.objectNode(); + String prevKey = null; + String presKey = null; + for(String key: element.keySet()){ + if(key.contains(".")){ + presKey = key.substring(0,key.indexOf(".")); + }else if(key.contains("@")){ + presKey = key.substring(0,key.indexOf("@")); + }else{ + presKey = key; + } + // first check if we are different from old. + System.out.println(key+"\n"); + if(jsonArray!=null && jsonArray.length()>0 && key.contains("@") && !key.contains(".") && oldValue!=null){ + if(!oldValue.equals(key.substring(0,key.indexOf("@")))){ + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + }else if(jsonArray!=null && jsonArray.length()>0 && !presKey.equals(prevKey) && oldValue!=null){ + jsonResult.put(oldValue, jsonArray); + isArray = false; + jsonArray = new JSONArray(); + } + /*if(node.size()!=0 && key.contains("@")){ + + }else{ + if(node.size()!=0){ + + } + }*/ + prevKey = presKey; + // + if(key.contains(".")){ + if(nodeKey==null){ + nodeKey = key.substring(0,key.indexOf(".")); + } + if(nodeKey.equals(key.substring(0,key.indexOf(".")))){ + node.put(key.substring(key.indexOf(".")+1), element.get(key)); + }else{ + if(node.size()!=0){ + if(nodeKey.contains("@")){ + if(arryKey==null){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + if(nodeKey.endsWith("@0")){ + isArray = true; + jsonArray = new JSONArray(); + } + if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ + jsonArray.put(decodeContent(node)); + } + if(key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))){ + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + }else if(!key.contains("@")){ + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + } + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + }else{ + isArray = false; + jsonResult.put(nodeKey, decodeContent(node)); + } + node = nodeFactory.objectNode(); + } + nodeKey = key.substring(0,key.indexOf(".")); + if(nodeKey.contains("@")){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + node.put(key.substring(key.indexOf(".")+1), element.get(key)); + } + }else if(node.size()!=0){ + if(nodeKey.contains("@")){ + if(arryKey==null){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + if(nodeKey.endsWith("@0")){ + isArray = true; + jsonArray = new JSONArray(); + } + if(arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ + jsonArray.put(decodeContent(node)); + } + jsonResult.put(arryKey, jsonArray); + jsonArray = new JSONArray(); + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + }else{ + isArray = false; + jsonResult.put(nodeKey, decodeContent(node)); + } + node = nodeFactory.objectNode(); + if(key.contains("@")){ + isArray = true; + if(key.endsWith("@0")|| jsonArray==null){ + jsonArray = new JSONArray(); + } + }else if(!key.contains("@")){ + isArray = false; + } + if(isArray){ + if(oldValue==null){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue!=prevKey){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue.equals(key.substring(0,key.indexOf("@")))){ + jsonArray.put(element.get(key)); + }else{ + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + oldValue = key.substring(0,key.indexOf("@")); + }else{ + jsonResult.put(key, element.get(key)); + } + }else{ + if(key.contains("@")){ + isArray = true; + if(key.endsWith("@0")|| jsonArray==null){ + jsonArray = new JSONArray(); + } + }else if(!key.contains("@")){ + isArray = false; + } + if(isArray){ + if(oldValue==null){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue!=prevKey){ + oldValue = key.substring(0,key.indexOf("@")); + } + if(oldValue.equals(key.substring(0,key.indexOf("@")))){ + jsonArray.put(element.get(key)); + }else{ + jsonResult.put(oldValue, jsonArray); + jsonArray = new JSONArray(); + } + oldValue = key.substring(0,key.indexOf("@")); + }else{ + jsonResult.put(key, element.get(key)); + } + } + } + if(node.size()>0){ + if(nodeKey.contains("@")){ + if(jsonArray==null){ + jsonArray = new JSONArray(); + } + if(arryKey==null){ + arryKey = nodeKey.substring(0,nodeKey.indexOf("@")); + } + jsonArray.put(decodeContent(node)); + jsonResult.put(arryKey, jsonArray); + isArray = false;; + }else{ + jsonResult.put(nodeKey, decodeContent(node)); + } + } + if(isArray && jsonArray.length() > 0){ + jsonResult.put(oldValue, jsonArray); + } + return jsonResult; + } + + public void PrePopulateDCAEMSPolicyData(PolicyAdapter policyAdapter) { + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("MS_") +3 , policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + String jsonBodyName = policyAdapter.getDirPath().replace(File.separator, ".")+ "." + policyAdapter.getOldPolicyFileName() + "."; + policyAdapter.setConfigBodyPath(jsonBodyName); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + int index = 0; + Iterator iterMatch = matchList.iterator(); + while (matchList.size()>1 && iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + + // First match in the target is EcompName, so set that value. + if (index == 0) { + policyAdapter.setEcompName(value); + } + if (index == 1){ + policyAdapter.setConfigName(value); + } + if (index == 2){ + if(value != null){ + readFile(policyAdapter); + } + } + if (index == 3){ + policyAdapter.setUuid(value); + } + if (index == 4){ + policyAdapter.setLocation(value); + } + if (index == 5){ + policyAdapter.setRiskType(value); + } + + if (index == 6){ + policyAdapter.setRiskLevel(value); + } + + if (index == 7){ + policyAdapter.setGuard(value); + } + if (index == 8 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + index++; + } + } + } + } + } + } + } + } + + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + @SuppressWarnings("unchecked") + private String readFile(PolicyAdapter policyAdapter) { + String fileLocation = null; + String policyScopeName = null; + String fileName = policyAdapter.getConfigBodyPath(); + if (fileName != null ) { + fileLocation = PolicyController.getConfigHome(); + } + if (fileLocation == null) { + return fileLocation; + } + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName)) { + FileInputStream inputStream = null; + String location = file.toString(); + try { + inputStream = new FileInputStream(location); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + if (location.endsWith("json")) { + JsonReader jsonReader = null; + jsonReader = Json.createReader(inputStream); + ObjectMapper mapper = new ObjectMapper(); + try { + DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(jsonReader.read().toString(), DCAEMicroServiceObject.class); + policyScopeName = getPolicyScope(msBody.getPolicyScope()); + policyAdapter.setPolicyScope(policyScopeName); + + policyAdapter.setPriority(msBody.getPriority()); + + if (msBody.getVersion()!= null){ + policyAdapter.setServiceType(msBody.getService() + "-v" + msBody.getVersion()); + }else{ + policyAdapter.setServiceType(msBody.getService()); + } + if(msBody.getContent() != null){ + LinkedHashMap data = new LinkedHashMap(); + LinkedHashMap map = (LinkedHashMap) msBody.getContent(); + readRecursivlyJSONContent(map, data); + policyAdapter.setRuleData(data); + } + + } catch (Exception e) { + e.printStackTrace(); + } + jsonReader.close(); + } + } + } + return fileName; + + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + private void readRecursivlyJSONContent(LinkedHashMap map, LinkedHashMap data){ + for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { + Object key = iterator.next(); + Object value = map.get(key); + if(value instanceof LinkedHashMap){ + readRecursivlyJSONContent((LinkedHashMap) value, data); + }else if(value instanceof ArrayList){ + ArrayList jsonArrayVal = (ArrayList)value; + for(int i = 0; i < jsonArrayVal.size(); i++){ + Object arrayvalue = jsonArrayVal.get(i); + if(arrayvalue instanceof LinkedHashMap){ + LinkedHashMap newData = new LinkedHashMap(); + readRecursivlyJSONContent((LinkedHashMap) arrayvalue, newData); + for(String objKey: newData.keySet()){ + data.put(key+"@"+i+"." +objKey, newData.get(objKey)); + } + }else if(arrayvalue instanceof ArrayList){ + ArrayList jsonArrayVal1 = (ArrayList)value; + for(int j = 0; j < jsonArrayVal1.size(); j++){ + Object arrayvalue1 = jsonArrayVal1.get(i); + data.put(key+"@"+j, arrayvalue1.toString()); + } + }else{ + data.put(key+"@"+i, arrayvalue.toString()); + } + } + }else{ + data.put(key.toString(), value.toString()); + } + } + } + + private String getPolicyScope(String value) { + GroupPolicyScopeList pScope = new GroupPolicyScopeList(); + List groupList= groupPolicyScopeListDao.getGroupPolicyScopeListData(); + if(groupList.size() > 0){ + for(int i = 0 ; i < groupList.size() ; i ++){ + pScope = groupList.get(i); + if (pScope.getGroupList().equals(value)){ + break; + } + } + } + return pScope.getGroupName(); + } + + private GroupPolicyScopeList getPolicyObject(String policyScope) { + GroupPolicyScopeList pScope = new GroupPolicyScopeList(); + List groupList = groupPolicyScopeListDao.getGroupPolicyScopeListData(); + if(groupList.size() > 0){ + for(int i = 0 ; i < groupList.size() ; i ++){ + pScope = groupList.get(i); + if (pScope.getGroupName().equals(policyScope)){ + break; + } + } + } + return pScope; + } + + private String constructJson(PolicyAdapter policyAdapter, String jsonContent) { + ObjectWriter om = new ObjectMapper().writer(); + String json=""; + DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject(); + + microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS)); + if(policyAdapter.getServiceType() !=null){ + microServiceObject.setService(policyAdapter.getServiceType().toString().split("-v")[0]); + if (policyAdapter.getServiceType().toString().contains("-v")){ + microServiceObject.setVersion(policyAdapter.getServiceType().toString().split("-v")[1]); + } + } + if(policyAdapter.getUuid()!=null){ + microServiceObject.setUuid(policyAdapter.getUuid()); + } + + if(policyAdapter.getLocation()!=null){ + microServiceObject.setLocation(policyAdapter.getLocation()); + } + if(policyAdapter.getPolicyName()!=null){ + microServiceObject.setPolicyName(policyAdapter.getPolicyName()); + } + + if(policyAdapter.getConfigName()!=null){ + microServiceObject.setConfigName(policyAdapter.getConfigName()); + } + if(policyAdapter.getPolicyDescription()!=null){ + microServiceObject.setDescription(policyAdapter.getPolicyDescription()); + } + if (policyAdapter.getPriority()!=null){ + microServiceObject.setPriority(policyAdapter.getPriority()); + }else { + microServiceObject.setPriority("9999"); + } + microServiceObject.setContent(jsonContent); + GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope()); + microServiceObject.setPolicyScope(policyScopeValue.getGroupList()); + try { + json = om.writeValueAsString(microServiceObject); + } catch (JsonProcessingException e) { + logger.error("Error writing out the object"); + } + System.out.println(json); + String cleanJson = cleanUPJson(json); + return cleanJson; + } + + private String cleanUPJson(String json) { + String cleanJason = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"}); + cleanJason = StringUtils.replaceEach(json, new String[]{"\\\\\\"}, new String[]{"\\"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"}); + + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"{", "}\""}, new String[]{"{", "}"}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""}); + cleanJason = StringUtils.replaceEach(cleanJason, new String[]{"\\\""}, new String[]{""}); + return cleanJason; + } + + //Convert the map values and set into JSON body + public Map convertMap(Map attributesMap, Map attributesRefMap) { + Map attribute = new HashMap(); + String temp = null; + String key; + String value; + for (Entry entry : attributesMap.entrySet()) { + key = entry.getKey(); + value = entry.getValue(); + attribute.put(key, value); + } + for (Entry entryRef : attributesRefMap.entrySet()) { + key = entryRef.getKey(); + value = entryRef.getValue().toString(); + attribute.put(key, value); + } + for (Entry entryList : attributesListRefMap.entrySet()) { + key = entryList.getKey(); + value = entryList.getValue().toString(); + attribute.put(key, value); + } + for (Entry> arrayList : arrayTextList.entrySet()){ + key = arrayList.getKey(); + temp = null; + for (Object textList : arrayList.getValue()){ + if (temp == null){ + temp = "[" + textList; + }else{ + temp = temp + "," + textList; + } + } + attribute.put(key, temp+ "]"); + } + + return attribute; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } +} + +class DCAEMicroServiceObject { + + public String service; + public String location; + public String uuid; + public String policyName; + public String description; + public String configName; + public String templateVersion; + public String version; + public String priority; + public String policyScope; + + public String getPolicyScope() { + return policyScope; + } + public void setPolicyScope(String policyScope) { + this.policyScope = policyScope; + } + + public String getPriority() { + return priority; + } + public void setPriority(String priority) { + this.priority = priority; + } + public String getVersion() { + return version; + } + public void setVersion(String version) { + this.version = version; + } + private Object content; + + + public String getPolicyName() { + return policyName; + } + public void setPolicyName(String policyName) { + this.policyName = policyName; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + public String getConfigName() { + return configName; + } + public void setConfigName(String configName) { + this.configName = configName; + } + public Object getContent() { + return content; + } + public void setContent(Object content) { + this.content = content; + } + + public String getService() { + return service; + } + public void setService(String service) { + this.service = service; + } + public String getLocation() { + return location; + } + public void setLocation(String location) { + this.location = location; + } + + public String getUuid() { + return uuid; + } + public void setUuid(String uuid) { + this.uuid = uuid; + } + public String getTemplateVersion() { + return templateVersion; + } + public void setTemplateVersion(String templateVersion) { + this.templateVersion = templateVersion; + } + +} \ No newline at end of file diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java new file mode 100644 index 000000000..6d7c0c752 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java @@ -0,0 +1,1292 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.SQLQuery; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.json.JSONObject; +import org.openecomp.policy.adapter.AddressGroupJson; +import org.openecomp.policy.adapter.AddressJson; +import org.openecomp.policy.adapter.AddressMembers; +import org.openecomp.policy.adapter.DeployNowJson; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.adapter.PrefixIPList; +import org.openecomp.policy.adapter.ServiceGroupJson; +import org.openecomp.policy.adapter.ServiceListJson; +import org.openecomp.policy.adapter.ServiceMembers; +import org.openecomp.policy.adapter.ServicesJson; +import org.openecomp.policy.adapter.Term; +import org.openecomp.policy.adapter.TermCollector; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.dao.AddressGroupDao; +import org.openecomp.policy.rest.dao.FirewallDictionaryListDao; +import org.openecomp.policy.rest.dao.PrefixListDao; +import org.openecomp.policy.rest.dao.SecurityZoneDao; +import org.openecomp.policy.rest.dao.ServiceGroupDao; +import org.openecomp.policy.rest.dao.ServiceListDao; +import org.openecomp.policy.rest.dao.TermListDao; +import org.openecomp.policy.rest.jpa.AddressGroup; +import org.openecomp.policy.rest.jpa.FirewallDictionaryList; +import org.openecomp.policy.rest.jpa.GroupServiceList; +import org.openecomp.policy.rest.jpa.PREFIXLIST; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.policy.rest.jpa.SecurityZone; +import org.openecomp.policy.rest.jpa.ServiceList; +import org.openecomp.policy.rest.jpa.TermList; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.core.JsonGenerationException; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.ObjectWriter; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreateFirewallController extends RestrictedBaseController { + private static Logger logger = FlexLogger.getLogger(CreateFirewallController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static PrefixListDao prefixListDao; + private static ServiceListDao serviceListDao; + private static TermListDao termListDao; + private static ServiceGroupDao serviceGroupDao; + private static AddressGroupDao addressGroupDao; + private static SecurityZoneDao securityZoneDao; + private static SessionFactory sessionFactory; + private static FirewallDictionaryListDao fwDictionaryListDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + List expandablePrefixIPList = new ArrayList(); + List expandableServicesList= new ArrayList(); + + private String parentSecurityZone; + + + public String getParentSecurityZone() { + return parentSecurityZone; + } + + public void setParentSecurityZone(String parentSecurityZone) { + this.parentSecurityZone = parentSecurityZone; + } + + + + @Autowired + private CreateFirewallController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, PrefixListDao prefixListDao, + ServiceListDao serviceListDao, TermListDao termListDao, ServiceGroupDao serviceGroupDao, AddressGroupDao addressGroupDao, SecurityZoneDao securityZoneDao, SessionFactory sessionFactory + ,FirewallDictionaryListDao fwDictionaryListDao, WatchPolicyNotificationDao policyNotificationDao){ + CreateFirewallController.addressGroupDao = addressGroupDao; + CreateFirewallController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreateFirewallController.policyVersionDao = policyVersionDao; + CreateFirewallController.prefixListDao = prefixListDao; + CreateFirewallController.serviceListDao = serviceListDao; + CreateFirewallController.termListDao = termListDao; + CreateFirewallController.serviceGroupDao = serviceGroupDao; + CreateFirewallController.securityZoneDao = securityZoneDao; + CreateFirewallController.sessionFactory = sessionFactory; + CreateFirewallController.fwDictionaryListDao = fwDictionaryListDao; + CreateFirewallController.policyNotificationDao = policyNotificationDao; + } + + public CreateFirewallController(){} + protected PolicyAdapter policyAdapter = null; + private List termCollectorList; + private List parentDictionaryList; + private String ruleID = ""; + private String jsonBody; + private ArrayList attributeList; + private ArrayList fwAttributeList; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/get_FWParentListDataByName"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getFWParentListEntityDataByName(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + String query= "select distinct parent from fwparent"; + model.put("fwParentListDictionaryDatas", mapper.writeValueAsString(queryToDatabase(query))); + + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @SuppressWarnings("unchecked") + private List queryToDatabase(String query) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List data = null; + try { + SQLQuery sqlquery=session.createSQLQuery(query); + //Query hbquery = session.createQuery(query); + data = sqlquery.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Qurying Parent Child Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + + } + + @SuppressWarnings("unchecked") + private void updateToDatabase(String updateQuery) { + Session session = sessionFactory.openSession(); + Transaction tx = session.beginTransaction(); + List data = null; + try { + SQLQuery sqlquery=session.createSQLQuery(updateQuery); + sqlquery.executeUpdate(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating FWChildParent Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @RequestMapping(value={"/policyController/save_FirewallPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveFirewallPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + termCollectorList = new ArrayList(); + parentDictionaryList= new ArrayList(); + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + this.policyAdapter = policyData; + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL); + policyData.setTtlDate(newDate); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_FW_" + policyData.getPolicyName(); + List policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + if(policyData.getFwPolicyType().equalsIgnoreCase("Parent Policy")){ + String comboNames=""; + int i=0; + for(Object fwattribute : policyData.getFwattributes()){ + if(fwattribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) fwattribute).get("option").toString(); + if(i>0){ + comboNames = comboNames+","+ key; + } + else{ + comboNames = key; + } + i++; + } + } + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"+"@comboList:"+comboNames); + } + else{ + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + } + + //policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map successMap = new HashMap(); + + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + termCollectorList.add(key); + } + } + } + if(policyData.getFwattributes()!=null){ + if(policyData.getFwattributes().size() > 0){ + for(Object fwattribute : policyData.getFwattributes()){ + if(fwattribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) fwattribute).get("option").toString(); + FirewallDictionaryList fwDictValue = fwDictionaryListDao.getFWDictionaryDataById(key); + parentDictionaryList.add(fwDictValue); + if(fwDictValue.getAddressList().contains(",")) { + for(String individualAddressObject:fwDictValue.getAddressList().split(",") ){ + expandablePrefixIPList.add(individualAddressObject); + } + } + else{ + expandablePrefixIPList.add(fwDictValue.getAddressList()); + } + + if(fwDictValue.getServiceList().contains(",")) { + for(String individualAddressObject:fwDictValue.getServiceList().split(",") ){ + expandableServicesList.add(individualAddressObject); + } + } + else{ + expandableServicesList.add(fwDictValue.getServiceList()); + } + } + } + } + } + + jsonBody = constructJson(); + if (jsonBody != null || jsonBody.equalsIgnoreCase("")) { + policyAdapter.setJsonBody(jsonBody); + + } else { + policyAdapter.setJsonBody("{}"); + } + policyData.setJsonBody(jsonBody); + + + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + removeExtension=removeExtension.replace(File.separator, "."); + //PC Feature + if(policyAdapter.getFwPolicyType().equalsIgnoreCase("Parent Policy")){ + //Reads the SecurityZone from the Parent UI and then gets the value from the DB + //Stores the Parent Policy Name and securityZone value to the fwparent table. + String parentSecurityZoneValue= getParentSecurityZone(); + String parentQuery= "INSERT INTO FWPARENT(PARENT,SECURITYZONE) VALUES ('"; + parentQuery=parentQuery+removeExtension+"','"+ parentSecurityZoneValue +"')"; + updateToDatabase(parentQuery); + } + else{ + String updateQuery = ""; + if(policyAdapter.isEditPolicy()){ + updateQuery= "UPDATE FWCHILDTOPARENT SET PARENT='"+policyAdapter.getParentForChild()+"' WHERE CHILD='"+removeExtension+"'"; + } + else{ + updateQuery= "INSERT INTO FWCHILDTOPARENT(CHILD,PARENT) VALUES ('"; + updateQuery =updateQuery+removeExtension+"','"+ policyAdapter.getParentForChild() +"')"; + } + updateToDatabase(updateQuery); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + private String convertDate(String dateTTL) { + String formateDate = null; + String[] date = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + private String constructJson() { + int ruleCount=1; + //Maps to assosciate the values read from the TermList dictionary + Map srcIP_map =null; + Map destIP_map=null; + Map srcPort_map =null; + Map destPort_map =null; + Map action_map=null; + Map fromZone_map=null; + Map toZone_map=null; + + String ruleDesc=null; + String ruleFromZone=null; + String ruleToZone=null; + String ruleSrcPrefixList=null; + String ruleDestPrefixList=null; + String ruleSrcPort=null; + String ruleDestPort=null; + String ruleAction=null; + + String json = null; + + + List expandableList = new ArrayList(); + TermList jpaTermList; + SecurityZone jpaSecurityZone; + List termList = new ArrayList(); + + ServiceListJson targetSl=null; + try{ + + for (int tl = 0 ; tl< termCollectorList.size(); tl++) { + expandableList.add(termCollectorList.get(tl)); + Term targetTerm = new Term(); + //targetSl= new ServiceListJson(); + targetTerm.setRuleName(termCollectorList.get(tl)); + List termListData = termListDao.getTermListData(); + for (int j =0; j < termListData.size(); j++) { + jpaTermList = termListData.get(j); + if (jpaTermList.getTermName().equals(termCollectorList.get(tl))){ + ruleDesc=jpaTermList.getTermDescription(); + if ((ruleDesc!=null)&& (!ruleDesc.isEmpty())){ + targetTerm.setDescription(ruleDesc); + } + ruleFromZone=jpaTermList.getFromZone(); + + if ((ruleFromZone != null) && (!ruleFromZone.isEmpty())){ + fromZone_map = new HashMap(); + fromZone_map.put(tl, ruleFromZone); + } + ruleToZone=jpaTermList.getToZone(); + + if ((ruleToZone != null) && (!ruleToZone.isEmpty())){ + toZone_map = new HashMap(); + toZone_map.put(tl, ruleToZone); + } + ruleSrcPrefixList=jpaTermList.getSrcIPList(); + + if ((ruleSrcPrefixList != null) && (!ruleSrcPrefixList.isEmpty())){ + srcIP_map = new HashMap(); + srcIP_map.put(tl, ruleSrcPrefixList); + } + + ruleDestPrefixList= jpaTermList.getDestIPList(); + if ((ruleDestPrefixList != null) && (!ruleDestPrefixList.isEmpty())){ + destIP_map = new HashMap(); + destIP_map.put(tl, ruleDestPrefixList); + } + + ruleSrcPort=jpaTermList.getSrcPortList(); + + if (ruleSrcPort != null && (!ruleSrcPort.isEmpty())){ + srcPort_map = new HashMap(); + srcPort_map.put(tl, ruleSrcPort); + } + + ruleDestPort= jpaTermList.getDestPortList(); + + if (ruleDestPort!= null && (!jpaTermList.getDestPortList().isEmpty())){ + destPort_map = new HashMap(); + destPort_map.put(tl, ruleDestPort); + } + + ruleAction=jpaTermList.getAction(); + + if (( ruleAction!= null) && (!ruleAction.isEmpty())){ + action_map = new HashMap(); + action_map.put(tl, ruleAction); + } + } + } + targetTerm.setEnabled(true); + targetTerm.setLog(true); + targetTerm.setNegateSource(false); + targetTerm.setNegateDestination(false); + + if(action_map!=null){ + targetTerm.setAction(action_map.get(tl)); + } + + //FromZone arrays + if(fromZone_map!=null){ + List fromZone= new ArrayList(); + for(String fromZoneStr:fromZone_map.get(tl).split(",") ){ + fromZone.add(fromZoneStr); + } + targetTerm.setFromZones(fromZone); + } + + //ToZone arrays + if(toZone_map!=null){ + List toZone= new ArrayList(); + for(String toZoneStr:toZone_map.get(tl).split(",") ){ + toZone.add(toZoneStr); + } + targetTerm.setToZones(toZone); + } + + //Destination Services. + if(destPort_map!=null){ + Set destServicesJsonList= new HashSet(); + for(String destServices:destPort_map.get(tl).split(",") ){ + ServicesJson destServicesJson= new ServicesJson(); + destServicesJson.setType("REFERENCE"); + if(destServices.equals("ANY")){ + destServicesJson.setName("any"); + destServicesJsonList.add(destServicesJson); + break; + }else{ + if(destServices.startsWith("Group_")){ + destServicesJson.setName(destServices.substring(6,destServices.length())); + } else{ + destServicesJson.setName(destServices); + } + destServicesJsonList.add(destServicesJson); + } + } + targetTerm.setDestServices(destServicesJsonList); + } + //ExpandableServicesList + if((srcPort_map!=null) && (destPort_map!=null)){ + String servicesCollateString = (srcPort_map.get(tl) + "," + destPort_map.get(tl)); + expandableServicesList.add(servicesCollateString); + }else if (srcPort_map!=null){ + expandableServicesList.add(srcPort_map.get(tl)); + }else if (destPort_map!=null){ + expandableServicesList.add(destPort_map.get(tl)); + } + + if(srcIP_map!=null){ + //Source List + List sourceListArrayJson= new ArrayList(); + for(String srcList:srcIP_map.get(tl).split(",") ){ + AddressJson srcListJson= new AddressJson(); + if(srcList.equals("ANY")){ + srcListJson.setType("any"); + sourceListArrayJson.add(srcListJson); + break; + }else{ + srcListJson.setType("REFERENCE"); + if(srcList.startsWith("Group_")){ + srcListJson.setValue(srcList.substring(6,srcList.length())); + }else{ + srcListJson.setValue(srcList); + } + sourceListArrayJson.add(srcListJson); + } + } + targetTerm.setSourceList(sourceListArrayJson); + } + if(destIP_map!=null){ + //Destination List + List destListArrayJson= new ArrayList(); + for(String destList:destIP_map.get(tl).split(",")){ + AddressJson destListJson= new AddressJson(); + if(destList.equals("ANY")){ + destListJson.setType("any"); + destListArrayJson.add(destListJson); + break; + }else{ + destListJson.setType("REFERENCE"); + if(destList.startsWith("Group_")){ + destListJson.setValue(destList.substring(6,destList.length())); + }else{ + destListJson.setValue(destList); + } + destListArrayJson.add(destListJson); + } + } + targetTerm.setDestinationList(destListArrayJson); + } + //ExpandablePrefixIPList + if ((srcIP_map!=null) && (destIP_map!=null)) + { + String collateString = (srcIP_map.get(tl) + "," + destIP_map + .get(tl)); + expandablePrefixIPList.add(collateString); + } + else if(srcIP_map!=null){ + expandablePrefixIPList.add(srcIP_map.get(tl)); + } + else if(destIP_map!=null){ + expandablePrefixIPList.add(destIP_map.get(tl)); + } + termList.add(targetTerm); + targetTerm.setPosition("" + (ruleCount++)); + } + TermCollector tc = new TermCollector(); + List securityZoneData = securityZoneDao.getSecurityZoneData(); + for (int j =0 ; j< securityZoneData.size() ; j++){ + jpaSecurityZone = securityZoneData.get(j); + if (jpaSecurityZone.getZoneName().equals(policyAdapter.getSecurityZone())){ + tc.setSecurityZoneId(jpaSecurityZone.getZoneValue()); + setParentSecurityZone(jpaSecurityZone.getZoneValue());//For storing the securityZone IDs to the DB + break; + } + } + + tc.setServiceTypeId("/v0/firewall/pan"); + tc.setConfigName(policyAdapter.getConfigName()); + + if(policyAdapter.getFwPolicyType().equalsIgnoreCase("Child Policy")){ + String securityZoneQuery="SELECT SECURITYZONE FROM FWPARENT WHERE PARENT='"; + securityZoneQuery=securityZoneQuery+policyAdapter.getParentForChild()+"'"; + List securityZoneValue= queryToDatabase(securityZoneQuery); + tc.setPrimaryParentZoneId(securityZoneValue.get(0)); + } + //Astra is rejecting the packet when it sees a new JSON field, so removing it for now. + //tc.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_FW)); + + DeployNowJson deployNow= new DeployNowJson(); + deployNow.setDeployNow(false); + + tc.setDeploymentOption(deployNow); + + Set servListArray = new HashSet(); + Set servGroupArray= new HashSet(); + Set addrGroupArray= new HashSet(); + + ServiceGroupJson targetSg= null; + AddressGroupJson addressSg=null; + ServiceListJson targetAny= null; + ServiceListJson targetAnyTcp=null; + ServiceListJson targetAnyUdp=null; + + for(String serviceList:expandableServicesList){ + for(String t: serviceList.split(",")){ + if((!t.startsWith("Group_"))){ + if(!t.equals("ANY")){ + ServiceList sl = new ServiceList(); + targetSl= new ServiceListJson(); + sl= mappingServiceList(t); + targetSl.setName(sl.getServiceName()); + targetSl.setDescription(sl.getServiceDescription()); + targetSl.setTransportProtocol(sl.getServiceTransProtocol()); + targetSl.setType(sl.getServiceType()); + targetSl.setPorts(sl.getServicePorts()); + servListArray.add(targetSl); + }else{ + //Any for destinationServices. + //Add names any, any-tcp, any-udp to the serviceGroup object. + targetAny= new ServiceListJson(); + targetAny.setName("any"); + targetAny.setType("SERVICE"); + targetAny.setTransportProtocol("any"); + targetAny.setPorts("any"); + + servListArray.add(targetAny); + + targetAnyTcp= new ServiceListJson(); + targetAnyTcp.setName("any-tcp"); + targetAnyTcp.setType("SERVICE"); + targetAnyTcp.setTransportProtocol("tcp"); + targetAnyTcp.setPorts("any"); + + servListArray.add(targetAnyTcp); + + targetAnyUdp= new ServiceListJson(); + targetAnyUdp.setName("any-udp"); + targetAnyUdp.setType("SERVICE"); + targetAnyUdp.setTransportProtocol("udp"); + targetAnyUdp.setPorts("any"); + + servListArray.add(targetAnyUdp); + } + }else{//This is a group + GroupServiceList sg= new GroupServiceList(); + targetSg= new ServiceGroupJson(); + sg= mappingServiceGroup(t); + + String name=sg.getGroupName(); + //Removing the "Group_" prepending string before packing the JSON + targetSg.setName(name.substring(6,name.length())); + List servMembersList= new ArrayList(); + + for(String groupString: sg.getServiceList().split(",")){ + ServiceMembers serviceMembers= new ServiceMembers(); + serviceMembers.setType("REFERENCE"); + serviceMembers.setName(groupString); + servMembersList.add(serviceMembers); + //Expand the group Name + ServiceList expandGroupSl = new ServiceList(); + targetSl= new ServiceListJson(); + expandGroupSl= mappingServiceList(groupString); + + targetSl.setName(expandGroupSl.getServiceName()); + targetSl.setDescription(expandGroupSl.getServiceDescription()); + targetSl.setTransportProtocol(expandGroupSl.getServiceTransProtocol()); + targetSl.setType(expandGroupSl.getServiceType()); + targetSl.setPorts(expandGroupSl.getServicePorts()); + servListArray.add(targetSl); + } + + targetSg.setMembers(servMembersList); + servGroupArray.add(targetSg); + + } + } + } + + Set prefixIPList = new HashSet(); + for(String prefixList:expandablePrefixIPList){ + for(String prefixIP: prefixList.split(",")){ + if((!prefixIP.startsWith("Group_"))){ + if(!prefixIP.equals("ANY")){ + List addMembersList= new ArrayList(); + List valueDesc= new ArrayList(); + PrefixIPList targetAddressList = new PrefixIPList(); + AddressMembers addressMembers= new AddressMembers(); + targetAddressList.setName(prefixIP); + + valueDesc = mapping(prefixIP); + targetAddressList.setDescription(valueDesc.get(1)); + + addressMembers.setType("SUBNET"); + addressMembers.setValue(valueDesc.get(0)); + + addMembersList.add(addressMembers); + + targetAddressList.setMembers(addMembersList); + prefixIPList.add(targetAddressList); + } + } + else{//This is a group + AddressGroup ag= new AddressGroup(); + addressSg= new AddressGroupJson(); + ag= mappingAddressGroup(prefixIP); + + String name=ag.getGroupName(); + //Removing the "Group_" prepending string before packing the JSON + addressSg.setName(name.substring(6,name.length())); + + List addrMembersList= new ArrayList(); + for(String groupString: ag.getPrefixList().split(",")){ + List valueDesc= new ArrayList(); + AddressMembers addressMembers= new AddressMembers(); + valueDesc= mapping (groupString); + if(valueDesc.size() > 0){ + addressMembers.setValue(valueDesc.get(0)); + } + addressMembers.setType("SUBNET"); + addrMembersList.add(addressMembers); + //Expand the group Name + } + addressSg.setMembers(addrMembersList); + addrGroupArray.add(addressSg); + } + + + } + } + + Set serviceGroup= new HashSet(); + + for(Object obj1:servGroupArray){ + serviceGroup.add(obj1); + } + + for(Object obj:servListArray){ + serviceGroup.add(obj); + } + + Set addressGroup= new HashSet(); + + for(Object addObj:prefixIPList){ + addressGroup.add(addObj); + } + + for(Object addObj1:addrGroupArray){ + addressGroup.add(addObj1); + } + + tc.setServiceGroups(serviceGroup); + tc.setAddressGroups(addressGroup); + tc.setFirewallRuleList(termList); + + + ObjectWriter om = new ObjectMapper().writer(); + try { + json = om.writeValueAsString(tc); + } catch (JsonGenerationException e) { + e.printStackTrace(); + } catch (JsonMappingException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + + }catch (Exception e) { + e.printStackTrace(); + } + + return json; + } + + private List mapping(String expandableList) { + String value = new String(); + String desc = new String(); + List valueDesc= new ArrayList(); + List prefixListData = prefixListDao.getPREFIXLISTData(); + for (int i = 0; i< prefixListData.size(); i++) { + PREFIXLIST prefixList = prefixListData.get(i); + if (prefixList.getPrefixListName().equals(expandableList)) { + value = prefixList.getPrefixListValue(); + valueDesc.add(value); + desc= prefixList.getDescription(); + valueDesc.add(desc); + break; + } + } + return valueDesc; + } + + private ServiceList mappingServiceList(String expandableList) { + ServiceList serviceList=null; + List serviceListData = serviceListDao.getServiceListData(); + for (int i = 0; i< serviceListData.size(); i++) { + serviceList = serviceListData.get(i); + if (serviceList.getServiceName().equals(expandableList)) { + break; + } + } + return serviceList; + } + + private GroupServiceList mappingServiceGroup(String expandableList) { + + GroupServiceList serviceGroup=null; + List serviceGroupData = serviceGroupDao.getGroupServiceListData(); + for (int i = 0; i< serviceGroupData.size(); i++) { + serviceGroup = serviceGroupData.get(i); + if (serviceGroup.getGroupName().equals(expandableList)) { + break; + } + } + return serviceGroup; + } + + private AddressGroup mappingAddressGroup(String expandableList) { + + AddressGroup addressGroup=null; + List addressGroupData = addressGroupDao.getAddressGroupData(); + for (int i = 0; i< addressGroupData.size(); i++) { + addressGroup = addressGroupData.get(i); + if (addressGroup.getGroupName().equals(expandableList)) { + break; + } + } + return addressGroup; + } + + public void PrePopulateFWPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList(); + fwAttributeList = new ArrayList(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + // policy name value is the policy name without any prefix and Extensions. + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("FW_") +3, policyAdapter.getPolicyName().lastIndexOf(".")); + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating form data for Config Policy selected:"+ policyAdapter.getPolicyName()); + } + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + + ObjectMapper mapper = new ObjectMapper(); + + TermCollector tc1=null; + BufferedReader br=null; + try { + //Json conversion. + String data=null; + SecurityZone jpaSecurityZone; + File file = new File(PolicyController.getConfigHome()+ File.separator+ policyAdapter.getDirPath().replace(File.separator, ".")+"."+ policyAdapter.getOldPolicyFileName() +".json"); + // Get data from this file using a file reader. + FileReader fr = new FileReader(file); + // To store the contents read via File Reader + br = new BufferedReader(fr); + // Read br and store a line in 'data', print data + data = br.readLine(); + tc1 = (TermCollector)mapper.readValue(data, TermCollector.class); + List securityZoneData = securityZoneDao.getSecurityZoneData(); + for (int i = 0; i < securityZoneData.size() ; i++) { + jpaSecurityZone = securityZoneData.get(i); + if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())){ + policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName()); + break; + } + } + if(tc1.getPrimaryParentZoneId()!=null)//Child policy + { + policyAdapter.setFwPolicyType("Child Policy"); + + String pathName=policyAdapter.getParentPath().toString(); + String scope= pathName.substring(pathName.lastIndexOf(File.separator)+1); + String fullPathName=scope+".Config_FW_"+policyNameValue; + + String query= "select parent from FWChildToParent where child='"; + query=query+fullPathName+"'"; + + List parentName=queryToDatabase(query); + policyAdapter.setParentForChild(parentName.get(0)); + + } + else{//Parent Policy + policyAdapter.setFwPolicyType("Parent Policy"); + //Retrieving the Dictionary combo list. + String desc = policy.getDescription(); + String descripComboList = desc.substring(desc.indexOf("@comboList:")+11,desc.length()) ; + Map parentMap = new HashMap(); + for(String value : descripComboList.split(",")){ + parentMap.put("option", value); + fwAttributeList.add(parentMap); + } + policyAdapter.setFwattributes(fwAttributeList); + } + } + catch(Exception e) { + logger.error("Exception Caused while Retriving the JSON body data" +e); + } + finally { + try { + if (br != null)br.close(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + + for (Term t : tc1.getFirewallRuleList()) { + Map termMap = new HashMap(); + termMap.put("option", t.getRuleName()); + attributeList.add(termMap); + } + policyAdapter.setAttributes(attributeList); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + int index = 0; + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attribute value and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + if (index == 1) { + policyAdapter.setConfigName(value); + } + if (index == 2){ + policyAdapter.setRiskType(value); + } + + if (index == 3){ + policyAdapter.setRiskLevel(value); + } + + if (index == 4){ + policyAdapter.setGuard(value); + } + if (index == 5 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + index++; + } + } + } + } + } + } + } + } + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + @RequestMapping(value={"/policyController/ViewFWPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView setFWViewRule(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + termCollectorList = new ArrayList(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").toString(), PolicyAdapter.class); + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + termCollectorList.add(key); + } + } + } + TermList jpaTermList; + String ruleSrcList=null; + String ruleDestList=null; + String ruleSrcPort=null; + String ruleDestPort=null; + String ruleAction=null; + List valueDesc= new ArrayList(); + StringBuffer displayString = new StringBuffer(); + for (String id : termCollectorList) { + jpaTermList = termListDao.getTermListValueByName(id); + if (jpaTermList != null){ + ruleSrcList= ((TermList) jpaTermList).getSrcIPList(); + if ((ruleSrcList!= null) && (!ruleSrcList.isEmpty()) && !ruleSrcList.equals("null")){ + displayString.append("Source IP List: " + ((TermList) jpaTermList).getSrcIPList()); + displayString.append(" ; \t\n"); + for(String srcList:ruleSrcList.split(",")){ + if(srcList.startsWith("Group_")){ + AddressGroup ag= new AddressGroup(); + ag= mappingAddressGroup(srcList); + displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n"); + for(String groupItems:ag.getPrefixList().split(",")){ + valueDesc=mapping(groupItems); + displayString.append("\n\t"+"Name: "+groupItems); + if(!valueDesc.isEmpty()){ + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + } + displayString.append("\n"); + } + }else{ + if(!srcList.equals("ANY")){ + valueDesc=mapping(srcList); + displayString.append("\n\t"+"Name: "+srcList); + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + displayString.append("\n"); + } + } + } + displayString.append("\n"); + } + ruleDestList= ((TermList) jpaTermList).getDestIPList(); + if ( ruleDestList!= null && (!ruleDestList.isEmpty())&& !ruleDestList.equals("null")){ + displayString.append("Destination IP List: " + ((TermList) jpaTermList).getDestIPList()); + displayString.append(" ; \t\n"); + for(String destList:ruleDestList.split(",")){ + if(destList.startsWith("Group_")){ + AddressGroup ag= new AddressGroup(); + ag= mappingAddressGroup(destList); + displayString.append("\n\t"+"Group has :"+ag.getPrefixList()+"\n"); + for(String groupItems:ag.getPrefixList().split(",")){ + valueDesc=mapping(groupItems); + displayString.append("\n\t"+"Name: "+groupItems); + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + displayString.append("\n\t"); + } + }else{ + if(!destList.equals("ANY")){ + valueDesc=mapping(destList); + displayString.append("\n\t"+"Name: "+destList); + displayString.append("\n\t"+"Description: "+valueDesc.get(1)); + displayString.append("\n\t"+"Value: "+valueDesc.get(0)); + displayString.append("\n\t"); + } + } + } + displayString.append("\n"); + } + + ruleSrcPort=((TermList) jpaTermList).getSrcPortList(); + if ( ruleSrcPort!= null && (!ruleSrcPort.isEmpty())&& !ruleSrcPort.equals("null")) { + displayString.append("\n"+"Source Port List:" + + ruleSrcPort); + displayString.append(" ; \t\n"); + } + + ruleDestPort= ((TermList) jpaTermList).getDestPortList(); + if (ruleDestPort != null && (!ruleDestPort.isEmpty())&& !ruleDestPort.equals("null")) { + displayString.append("\n"+"Destination Port List:" + + ruleDestPort); + displayString.append(" ; \t\n"); + for(String destServices:ruleDestPort.split(",")){ + if(destServices.startsWith("Group_")){ + GroupServiceList sg= new GroupServiceList(); + sg= mappingServiceGroup(destServices); + displayString.append("\n\t"+"Service Group has :"+sg.getServiceList()+"\n"); + for(String groupItems:sg.getServiceList().split(",")){ + ServiceList sl= new ServiceList(); + sl= mappingServiceList(groupItems); + displayString.append("\n\t"+"Name: "+ + sl.getServiceName()); + displayString.append("\n\t"+"Description: "+ + sl.getServiceDescription()); + displayString.append("\n\t"+"Transport-Protocol: "+ + sl.getServiceTransProtocol()); + displayString.append("\n\t"+"Ports: "+ + sl.getServicePorts()); + displayString.append("\n"); + } + } + else{ + if(!destServices.equals("ANY")){ + ServiceList sl= new ServiceList(); + sl= mappingServiceList(destServices); + displayString.append("\n\t"+"Name: "+ + sl.getServiceName()); + displayString.append("\n\t"+"Description: "+ + sl.getServiceDescription()); + displayString.append("\n\t"+"Transport-Protocol: "+ + sl.getServiceTransProtocol()); + displayString.append("\n\t"+"Ports: "+ + sl.getServicePorts()); + displayString.append("\n"); + } + } + } + displayString.append("\n"); + } + + ruleAction=(jpaTermList).getAction(); + if ( ruleAction!= null && (!ruleAction.isEmpty())) { + displayString.append("\n"+"Action List:" + + ruleAction); + displayString.append(" ; \t\n"); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(displayString); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + return null; + } + + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java new file mode 100644 index 000000000..f5c0a576c --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java @@ -0,0 +1,484 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +@Controller +@RequestMapping("/") +public class CreatePolicyController extends RestrictedBaseController{ + private static Logger logger = FlexLogger.getLogger(CreatePolicyController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private CreatePolicyController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){ + CreatePolicyController.policyVersionDao = policyVersionDao; + CreatePolicyController.ruleAlgorithmsDao = ruleAlgorithmsDao; + CreatePolicyController.policyNotificationDao = policyNotificationDao; + } + + public CreatePolicyController(){} + + protected PolicyAdapter policyAdapter = null; + private String ruleID = ""; + private ArrayList attributeList; + boolean isValidForm = false; + private int riskLevelCount; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/get_RiskLevelValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getRiskLevelValuesData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + List riskLevelList = new ArrayList(); + riskLevelCount = 5; + for (int i = 1; i <= riskLevelCount; i++) { + riskLevelList.add(String.valueOf(i)); + } + model.put("riskLevelDatas", mapper.writeValueAsString(riskLevelList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_GuardlValues"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getGuardValuesData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + List guardList = new ArrayList(); + guardList.add("True"); + guardList.add("False"); + model.put("guardDatas", mapper.writeValueAsString(guardList)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + + @RequestMapping(value={"/policyController/save_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + + if (policyData.getTtlDate()==null){ + policyData.setTtlDate("NA"); + }else{ + String dateTTL = policyData.getTtlDate(); + String newDate = convertDate(dateTTL, false); + policyData.setTtlDate(newDate); + } + + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Config_" + policyData.getPolicyName(); + List policyVersionlist = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionlist.size() > 0) { + for(int i = 0; i < policyVersionlist.size(); i++) { + PolicyVersion entityItem = policyVersionlist.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + + Map successMap = new HashMap(); + Map attributeMap = new HashMap(); + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List ruleAlgorithmList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + String value = ((LinkedHashMap) attribute).get("number").toString(); + attributeMap.put(key, value); + } + } + } + policyData.setDynamicFieldConfigAttributes(attributeMap); + + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List versionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (versionList.size() > 0) { + for(int i = 0; i < versionList.size(); i++) { + PolicyVersion entityItem = versionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + private String convertDate(String dateTTL, boolean portalType) { + String formateDate = null; + String[] date; + String[] parts; + + if (portalType){ + parts = dateTTL.split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0] + "T05:00:00.000Z"; + } else { + date = dateTTL.split("T"); + parts = date[0].split("-"); + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + } + return formateDate; + } + + public void PrePopulateBaseConfigPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + policyAdapter.setConfigBodyData(readBaseConfigJSONFile(policyAdapter)); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1 , policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy. + TargetType target = policy.getTarget(); + if (target != null) { + // Under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AnyOFType we have AllOFType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + int index = 0; + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOFType we have Match + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is EcompName, so set that value. + if (index == 1) { + policyAdapter.setEcompName(value); + } + if (index == 2){ + policyAdapter.setRiskType(value); + } + + if (index == 3){ + policyAdapter.setRiskLevel(value); + } + + if (index == 4){ + policyAdapter.setGuard(value); + } + if (index == 5 && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + if (index == 6){ + policyAdapter.setConfigName(value); + } + // After Ecomp and Config it is optional to have attributes, so + // check weather dynamic values or there or not. + if (index >= 7) { + Map attribute = new HashMap(); + attribute.put("option", attributeId); + attribute.put("number", value); + attributeList.add(attribute); + } + index++; + } + } + } + } + } + } + + policyAdapter.setAttributes(attributeList); + } + List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + for (Object o : ruleList) { + if (o instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + policyAdapter.setRuleID(((RuleType) o).getRuleId()); + } + } + } + } + + private String readBaseConfigJSONFile(PolicyAdapter policyAdapter) { + String fileName = policyAdapter.getPolicyName(); + String fileLocation = null; + if (fileName != null && fileName.contains("Config")) { + fileLocation = PolicyController.getConfigHome(); + } + if (logger.isDebugEnabled()) { + logger.debug("Attempting to read file from the location: " + fileLocation); + } + + if (fileLocation == null) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error with the FileName: " + fileName); + return fileLocation; + } + + + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + String extension = null; + for (File file : listOfFiles) { + if (file.isFile() && file.getName().contains(fileName)) { + // For config form we have set the ConfigType Based on the extention. + if (fileName.contains("Config")) { + extension = file.getName().substring(file.getName().lastIndexOf('.') + 1); + // Based on file type set Combobox config value + if (extension.equals("txt")) { + policyAdapter.setConfigType("OTHER"); + } else { + policyAdapter.setConfigType(extension.toUpperCase()); + } + } + // Reading the file + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + return sb.toString(); + } catch (FileNotFoundException e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); + } catch (IOException e1) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e1.getMessage()); + } + } + } + return null; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DashboardController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DashboardController.java new file mode 100644 index 000000000..301c824f0 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DashboardController.java @@ -0,0 +1,430 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.management.AttributeNotFoundException; +import javax.management.InstanceNotFoundException; +import javax.management.MBeanException; +import javax.management.MalformedObjectNameException; +import javax.management.ObjectName; +import javax.management.ReflectionException; +import javax.management.remote.JMXConnector; +import javax.management.remote.JMXConnectorFactory; +import javax.management.remote.JMXServiceURL; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +//import org.apache.commons.logging.Log; +//import org.apache.commons.logging.LogFactory; +import org.json.JSONObject; +import org.openecomp.policy.dao.SystemLogDbDao; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDP; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDP; +import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class DashboardController extends RestrictedBaseController{ + private static final Logger logger = FlexLogger.getLogger(DashboardController.class); + @Autowired + SystemLogDbDao systemDAO; + + private int pdpCount; + private PDPGroupContainer pdpConatiner; + private ArrayList pdpStatusData; + private ArrayList papStatusData; + private ArrayList policyActivityData; + + + + @RequestMapping(value={"/get_DashboardLoggingData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("availableLoggingDatas", mapper.writeValueAsString(systemDAO.getLoggingData())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_DashboardSystemAlertData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getSystemAlertData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("systemAlertsTableDatas", mapper.writeValueAsString(systemDAO.getSystemAlertData())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_DashboardPAPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPAPStatusData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + addPAPToTable(); + model.put("papTableDatas", mapper.writeValueAsString(papStatusData)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_DashboardPDPStatusData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPDPStatusData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine()); + addPDPToTable(); + model.put("pdpTableDatas", mapper.writeValueAsString(pdpStatusData)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/get_DashboardPolicyActivityData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyActivityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + this.pdpConatiner = new PDPGroupContainer(PolicyController.getPapEngine()); + addPolicyToTable(); + model.put("policyActivityTableDatas", mapper.writeValueAsString(policyActivityData)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + /* + * Add the PAP information to the PAP Table + */ + public void addPAPToTable(){ + papStatusData = new ArrayList(); + File folder = new File(PolicyController.getGitPath().toAbsolutePath().toString()); + String papStatus = null; + try { + Set groups = PolicyController.getPapEngine().getEcompPDPGroups(); + if (groups == null) { + papStatus = "UNKNOWN"; + throw new PAPException("PAP not running"); + }else { + papStatus = "IS_OK"; + } + } catch (PAPException | NullPointerException e1) { + papStatus = "CANNOT_CONNECT"; + logger.error("Error getting PAP status, PAP not responding to requests"); + } + String papURL = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + JSONObject object = new JSONObject(); + object.put("system", papURL); + object.put("status", papStatus); + object.put("noOfPolicy", countFilesInDirectory(folder)); + object.put("noOfConnectedTrap", pdpCount); + papStatusData.add(0, object); + } + + private int countFilesInDirectory(File directory) { + int count = 0; + for (File file : directory.listFiles()) { + if (file.isFile() && file.getName().endsWith(".xml")) { + count++; + } + if (file.isDirectory()) { + count += countFilesInDirectory(file); + } + } + return count; + } + /** + * Add PDP Information to the PDP Table + * + */ + public void addPDPToTable(){ + pdpCount = 0; + pdpStatusData = new ArrayList(); + long naCount; + long denyCount = 0; + long permitCount = 0; + for (PDPGroup group : this.pdpConatiner.getGroups()){ + for (PDP pdp : group.getPdps()){ + naCount = -1; + if (pdp.getStatus().getStatus().toString() == "UP_TO_DATE" && ((EcompPDP) pdp).getJmxPort() != 0){ + String pdpIpAddress = parseIPSystem(pdp.getId()); + int port = ((EcompPDP) pdp).getJmxPort(); + if (port != 0) + logger.debug("Getting JMX Response Counts from " + pdpIpAddress + " at JMX port " + port); + naCount = getRequestCounts(pdpIpAddress, port, "pdpEvaluationNA"); + permitCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationPermit"); + denyCount = getRequestCounts(pdpIpAddress, port, "PdpEvaluationDeny"); + } + if (naCount == -1){ + JSONObject object = new JSONObject(); + object.put("id", pdp.getId()); + object.put("name", pdp.getName()); + object.put("groupname", group.getName()); + object.put("status", pdp.getStatus().getStatus().toString()); + object.put("description", pdp.getDescription()); + object.put("permitCount", "NA"); + object.put("denyCount", "NA"); + object.put("naCount", "NA"); + pdpStatusData.add(object); + }else{ + JSONObject object = new JSONObject(); + object.put("id", pdp.getId()); + object.put("name", pdp.getName()); + object.put("groupname", group.getName()); + object.put("status", pdp.getStatus().getStatus().toString()); + object.put("description", pdp.getDescription()); + object.put("permitCount", permitCount); + object.put("denyCount", denyCount); + object.put("naCount", naCount); + pdpStatusData.add(object); + } + pdpCount++; + } + } + } + + private static String parseIPSystem(String line) { + Pattern pattern = Pattern.compile("://(.+?):"); + Matcher ip = pattern.matcher(line); + if (ip.find()) + { + return ip.group(1); + } + return null; + } + + /* + * Contact JMX Connector Sever and return the value of the given jmxAttribute + */ + @SuppressWarnings("rawtypes") + private long getRequestCounts(String host, int port, String jmxAttribute) { + + logger.debug("Create an RMI connector client and connect it to the JMX connector server"); + HashMap map = new HashMap(); + map = null; + JMXConnector jmxConnection; + try { + jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map); + jmxConnection.connect(); + Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), jmxAttribute); + jmxConnection.close(); + logger.debug("pdpEvaluationNA value retreived: " + o); + return (long) o; + } catch (MalformedURLException e) { + logger.error("MalformedURLException for JMX connection"); + } catch (IOException e) { + logger.error("Error in reteriving" + jmxAttribute + " from JMX connection"); + } catch (AttributeNotFoundException e) { + logger.error("AttributeNotFoundException " + jmxAttribute + " for JMX connection"); + } catch (InstanceNotFoundException e) { + logger.error("InstanceNotFoundException " + host + " for JMX connection"); + } catch (MalformedObjectNameException e) { + logger.error("MalformedObjectNameException for JMX connection"); + } catch (MBeanException e) { + logger.error("MBeanException for JMX connection"); + e.printStackTrace(); + } catch (ReflectionException e) { + logger.error("ReflectionException for JMX connection"); + } + + return -1; + } + + private static JMXServiceURL createConnectionURL(String host, int port) throws MalformedURLException{ + return new JMXServiceURL("rmi", "", 0, "/jndi/rmi://" + host + ":" + port + "/jmxrmi"); + } + + + /* + * Add the information to the Policy Table + */ + private void addPolicyToTable() { + policyActivityData = new ArrayList(); + int i = 1; + String policyID = null; + int policyFireCount = 0; + Map policyMap = new HashMap<>(); + Object policyList = null; + //get list of policy + + for (PDPGroup group : this.pdpConatiner.getGroups()){ + for (PDPPolicy policy : group.getPolicies()){ + try{ + policyMap.put(policy.getPolicyId().replace(" ", ""), policy.getId()); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e); + } + } + + for (PDP pdp : group.getPdps()){ + // Add rows to the Policy Table + policyList = null; + if (pdp.getStatus().getStatus().toString() == "UP_TO_DATE" && ((EcompPDP) pdp).getJmxPort() != 0){ + String pdpIpAddress = parseIPSystem(pdp.getId()); + policyList = getPolicy(pdpIpAddress, ((EcompPDP) pdp).getJmxPort(), "policyCount"); + } + if (policyList != null && policyList.toString().length() > 3){ + String[] splitPolicy = policyList.toString().split(","); + for (String policyKeyValue : splitPolicy){ + policyID = urnPolicyID(policyKeyValue); + policyFireCount = countPolicyID(policyKeyValue); + if (policyID != null ){ + if (policyMap.containsKey(policyID)){ + JSONObject object = new JSONObject(); + object.put("policyId", policyMap.get(policyID)); + object.put("fireCount", policyFireCount); + object.put("system", pdp.getId()); + policyActivityData.add(i, object); + i++; + } + } + } + }else { + if (policyList != null){ + JSONObject object = new JSONObject(); + object.put("policyId", "Unable to retrieve policy information"); + object.put("fireCount", "NA"); + object.put("system", pdp.getId()); + policyActivityData.add(i, object); + i++; + }else{ + JSONObject object = new JSONObject(); + object.put("policyId", "Unable to access PDP JMX Server"); + object.put("fireCount", "NA"); + object.put("system", pdp.getId()); + policyActivityData.add(i, object); + i++; + } + } + + } + } + } + + /* + * Contact JMX Connector Sever and return the list of {policy id , count} + */ + @SuppressWarnings("rawtypes") + private Object getPolicy(String host, int port, String jmxAttribute){ + logger.debug("Create an RMI connector client and connect it to the JMX connector server for Policy: " + host); + HashMap map = new HashMap(); + map = null; + JMXConnector jmxConnection; + try { + jmxConnection = JMXConnectorFactory.newJMXConnector(createConnectionURL(host, port), map); + jmxConnection.connect(); + Object o = jmxConnection.getMBeanServerConnection().getAttribute(new ObjectName("PdpRest:type=PdpRestMonitor"), "policyMap"); + jmxConnection.close(); + logger.debug("policyMap value retreived: " + o); + return o; + } catch (MalformedURLException e) { + logger.error("MalformedURLException for JMX connection"); + } catch (IOException e) { + logger.error("AttributeNotFoundException for policyMap" ); + } catch (AttributeNotFoundException e) { + logger.error("AttributeNotFoundException for JMX connection"); + } catch (InstanceNotFoundException e) { + logger.error("InstanceNotFoundException " + host + " for JMX connection"); + } catch (MalformedObjectNameException e) { + logger.error("MalformedObjectNameException for JMX connection"); + } catch (MBeanException e) { + logger.error("MBeanException for JMX connection"); + e.printStackTrace(); + } catch (ReflectionException e) { + logger.error("ReflectionException for JMX connection"); + } + + return null; + + } + + private static String urnPolicyID(String line){ + String[] splitLine = line.toString().split("="); + String removeSpaces = splitLine[0].replaceAll("\\s+", ""); + return removeSpaces.replace("{", ""); + } + + private static Integer countPolicyID(String line){ + String[] splitLine = line.toString().split("="); + String sCount = splitLine[1].replace("}", ""); + int intCount = Integer.parseInt(sCount); + return intCount; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java new file mode 100644 index 000000000..20cde7f43 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java @@ -0,0 +1,507 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RuleAlgorithmsDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.elk.client.PolicyElasticSearchController; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.RuleAlgorithms; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import com.att.research.xacml.api.XACML3; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Joiner; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; + +@Controller +@RequestMapping("/") +public class DecisionPolicyController extends RestrictedBaseController { + private static final Logger logger = FlexLogger.getLogger(DecisionPolicyController.class); + + private static RuleAlgorithmsDao ruleAlgorithmsDao; + private static PolicyVersionDao policyVersionDao; + private static WatchPolicyNotificationDao policyNotificationDao; + + @Autowired + private DecisionPolicyController(RuleAlgorithmsDao ruleAlgorithmsDao, PolicyVersionDao policyVersionDao, WatchPolicyNotificationDao policyNotificationDao){ + DecisionPolicyController.policyVersionDao = policyVersionDao; + DecisionPolicyController.ruleAlgorithmsDao = ruleAlgorithmsDao; + DecisionPolicyController.policyNotificationDao = policyNotificationDao; + } + + public DecisionPolicyController(){} + + protected PolicyAdapter policyAdapter = null; + private static String ruleID = ""; + private ArrayList attributeList; + private ArrayList decisionList; + private ArrayList ruleAlgorithmList; + protected LinkedList ruleAlgoirthmTracker; + public static final String FUNCTION_NOT = "urn:oasis:names:tc:xacml:1.0:function:not"; + + public String newPolicyID() { + return Joiner.on(':').skipNulls().join((PolicyController.getDomain().startsWith("urn") ? null: "urn"), + PolicyController.getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); + } + + @RequestMapping(value={"/policyController/save_DecisionPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView saveDecisionPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + String userId = UserUtils.getUserIdFromCookie(request); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyAdapter.class); + if(root.get("policyData").get("model").get("type").toString().replace("\"", "").equals("file")){ + policyData.isEditPolicy = true; + } + if(root.get("policyData").get("model").get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get("policyData").get("model").get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get("policyData").get("model").get("path").get(i).toString().replace("\"", "") + File.separator; + } + policyData.setDomainDir(dirName.substring(0, dirName.lastIndexOf(File.separator))); + }else{ + policyData.setDomainDir(root.get("policyData").get("model").get("name").toString().replace("\"", "")); + } + int version = 0; + int highestVersion = 0; + int descriptionVersion = 0; + //get the highest version of policy from policy version table. + //getting the sub scope domain where the policy is created or updated + String dbCheckPolicyName = policyData.getDomainDir() + File.separator + "Decision_" + policyData.getPolicyName(); + List policyVersionList = policyVersionDao.getPolicyVersionEntityByName(dbCheckPolicyName); + if (policyVersionList.size() > 0) { + for(int i = 0; i < policyVersionList.size(); i++) { + PolicyVersion entityItem = policyVersionList.get(i); + if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + highestVersion = entityItem.getHigherVersion(); + } + } + } + if(highestVersion != 0){ + version = highestVersion; + descriptionVersion = highestVersion +1; + }else{ + version = 1; + descriptionVersion = 1; + } + + //set policy adapter values for Building JSON object containing policy data + String createdBy = ""; + String modifiedBy = userId; + if(descriptionVersion == 1){ + createdBy = userId; + }else{ + String policyName = PolicyController.getGitPath().toAbsolutePath().toString() + File.separator + policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + File policyPath = new File(policyName); + try { + createdBy = XACMLPolicyScanner.getCreatedBy(policyPath.toPath()); + } catch (IOException e) { + createdBy = "guest"; + } + } + + policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + Map successMap = new HashMap(); + Map attributeMap = new HashMap(); + Map settingsMap = new HashMap(); + + List dynamicRuleAlgorithmLabels = new LinkedList(); + List dynamicRuleAlgorithmCombo = new LinkedList(); + List dynamicRuleAlgorithmField1 = new LinkedList(); + List dynamicRuleAlgorithmField2 = new LinkedList(); + List dynamicVariableList = new LinkedList(); + List dataTypeList = new LinkedList(); + + //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + List ruleAlgorithmsList = ruleAlgorithmsDao.getRuleAlgorithms(); + for (int i = 0; i < ruleAlgorithmsList.size(); i++) { + RuleAlgorithms a = ruleAlgorithmsList.get(i); + if (a.getXacmlId().equals(XACML3.ID_RULE_PERMIT_OVERRIDES.stringValue())) { + policyData.setRuleCombiningAlgId(a.getXacmlId()); + break; + } + } + + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("option").toString(); + String value = ((LinkedHashMap) attribute).get("number").toString(); + attributeMap.put(key, value); + } + } + } + + if(policyData.getSettings().size() > 0){ + for(Object settingsData : policyData.getSettings()){ + if(settingsData instanceof LinkedHashMap){ + String key = ((LinkedHashMap) settingsData).get("option").toString(); + String value = ((LinkedHashMap) settingsData).get("number").toString(); + settingsMap.put(key, value); + } + } + } + + if(policyData.getRuleAlgorithmschoices().size() > 0){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap){ + String label = ((LinkedHashMap) attribute).get("id").toString(); + String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); + dynamicRuleAlgorithmLabels.add(label); + dynamicRuleAlgorithmField1.add(key); + dynamicRuleAlgorithmCombo.add(rule); + dynamicRuleAlgorithmField2.add(value); + } + } + } + + policyData.setDynamicRuleAlgorithmLabels(dynamicRuleAlgorithmLabels); + policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); + policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); + policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); + policyData.setDynamicVariableList(dynamicVariableList); + policyData.setDynamicSettingsMap(settingsMap); + policyData.setDynamicFieldConfigAttributes(attributeMap); + policyData.setDataTypeList(dataTypeList); + if (policyData.isEditPolicy()){ + //increment the version and set in policyAdapter + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + policyData.setPolicyID(this.newPolicyID()); + policyData.setRuleID(ruleID); + successMap = engine.updatePolicyRequest(policyData); + } else { + //send it for policy creation + policyData.setVersion(String.valueOf(version)); + policyData.setHighestVersion(version); + successMap = engine.createPolicyRequest(policyData); + + } + + if (successMap.containsKey("success")) { + // Add it into our tree + Path finalPolicyPath = null; + finalPolicyPath = Paths.get(successMap.get("success")); + PolicyElasticSearchController controller = new PolicyElasticSearchController(); + controller.updateElk(finalPolicyPath.toString()); + File file = finalPolicyPath.toFile(); + if(file != null){ + String policyName = file.toString(); + String removePath = policyName.substring(policyName.indexOf("repository")+11); + String removeXml = removePath.replace(".xml", ""); + String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + List vesionList = policyVersionDao.getPolicyVersionEntityByName(removeExtension); + if (vesionList.size() > 0) { + for(int i = 0; i < vesionList.size(); i++) { + PolicyVersion entityItem = vesionList.get(i); + if(entityItem.getPolicyName().equals(removeExtension)){ + version = entityItem.getHigherVersion() +1; + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setModifiedBy(userId); + policyVersionDao.update(entityItem); + if(policyData.isEditPolicy){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; + email.sendMail(entityItem, policyNameForEmail, mode, policyNotificationDao); + } + } + } + }else{ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(version); + entityItem.setHigherVersion(version); + entityItem.setPolicyName(removeExtension); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + policyVersionDao.Save(entityItem); + } + } + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + public void PrePopulateDecisionPolicyData(PolicyAdapter policyAdapter) { + attributeList = new ArrayList(); + decisionList = new ArrayList(); + ruleAlgorithmList = new ArrayList(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1, policyAdapter.getPolicyName().lastIndexOf(".")); + policyAdapter.setPolicyName(policyNameValue); + String description = ""; + try{ + description = policy.getDescription().substring(0, policy.getDescription().indexOf("@CreatedBy:")); + }catch(Exception e){ + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + // Get the target data under policy for Action. + TargetType target = policy.getTarget(); + if (target != null) { + // under target we have AnyOFType + List anyOfList = target.getAnyOf(); + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + // Under AntOfType we have AllOfType + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + // Under AllOfType we have Mathch. + List matchList = allOf.getMatch(); + int index = 0; + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Under the match we have attributevalue and + // attributeDesignator. So,finally down to the actual attribute. + // + AttributeValueType attributeValue = match.getAttributeValue(); + String value = (String) attributeValue.getContent().get(0); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is EcompName, so set that value. + if (index == 0) { + policyAdapter.setEcompName(value); + } + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic componet at index 0. + if (index >= 1) { + Map attribute = new HashMap(); + attribute.put("option", attributeId); + attribute.put("number", value); + attributeList.add(attribute); + } + index++; + } + } + policyAdapter.setAttributes(attributeList); + } + } + } + } + + List ruleList = policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition(); + int index = 0; + for (Object object : ruleList) { + if (object instanceof VariableDefinitionType) { + VariableDefinitionType variableDefinitionType = (VariableDefinitionType) object; + Map settings = new HashMap(); + settings.put("option", variableDefinitionType.getVariableId()); + JAXBElement attributeValueTypeElement = (JAXBElement) variableDefinitionType.getExpression(); + if (attributeValueTypeElement != null) { + AttributeValueType attributeValueType = attributeValueTypeElement.getValue(); + settings.put("number", attributeValueType.getContent().get(0).toString()); + } + decisionList.add(settings); + } else if (object instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + ruleID = ((RuleType) object).getRuleId(); + if (((RuleType) object).getEffect().equals(EffectType.PERMIT)) { + ConditionType condition = ((RuleType) object).getCondition(); + if (condition != null) { + ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); + ruleAlgoirthmTracker = new LinkedList(); + // Populating Rule Algorithms starting from compound. + prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } + }else if(((RuleType) object).getEffect().equals(EffectType.DENY)) { + if(((RuleType) object).getAdviceExpressions()!=null){ + if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("AAF")){ + policyAdapter.setRuleProvider("AAF"); + break; + } + }else{ + policyAdapter.setRuleProvider("Custom"); + } + } + } + } + } + policyAdapter.setSettings(decisionList); + } + + } + + private void prePopulateDecisionRuleAlgorithms(int index, ApplyType decisionApply, List> jaxbDecisionTypes) { + Map ruleMap = new HashMap(); + ruleMap.put("id", "A" + (index +1)); + Map dropDownMap = PolicyController.getDropDownMap(); + for (String key : dropDownMap.keySet()) { + String keyValue = dropDownMap.get(key); + if (keyValue.equals(decisionApply.getFunctionId())) { + ruleMap.put("dynamicRuleAlgorithmCombo", key); + } + } + // Populate the key and value fields + if (((jaxbDecisionTypes.get(0).getValue()) instanceof AttributeValueType)) { + ApplyType innerDecisionApply = (ApplyType) jaxbDecisionTypes.get(1).getValue(); + List> jaxbInnerDecisionTypes = innerDecisionApply.getExpression(); + if (jaxbInnerDecisionTypes.get(0).getValue() instanceof AttributeDesignatorType) { + AttributeDesignatorType attributeDesignator = (AttributeDesignatorType) jaxbInnerDecisionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", attributeDesignator.getAttributeId()); + + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(0).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + } else if ((jaxbDecisionTypes.get(0).getValue()) instanceof VariableReferenceType) { + VariableReferenceType variableReference = (VariableReferenceType) jaxbDecisionTypes.get(0).getValue(); + ruleMap.put("dynamicRuleAlgorithmField1", "S_"+ variableReference.getVariableId()); + + + // Get from Attribute Value + AttributeValueType actionConditionAttributeValue = (AttributeValueType) jaxbDecisionTypes.get(1).getValue(); + String attributeValue = (String) actionConditionAttributeValue.getContent().get(0); + ruleMap.put("dynamicRuleAlgorithmField2", attributeValue); + } + ruleAlgorithmList.add(ruleMap); + } + + private int prePopulateDecisionCompoundRuleAlgorithm(int index, ApplyType decisionApply) { + boolean isCompoundRule = true; + List> jaxbDecisionTypes = decisionApply.getExpression(); + for (JAXBElement jaxbElement : jaxbDecisionTypes) { + // If There is Attribute Value under Decision Type that means we came to the final child + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating rule algoirthm: " + index); + } + // Check to see if Attribute Value exists, if yes then it is not a compound rule + if(jaxbElement.getValue() instanceof AttributeValueType) { + prePopulateDecisionRuleAlgorithms(index, decisionApply, jaxbDecisionTypes); + ruleAlgoirthmTracker.addLast(index); + isCompoundRule = false; + index++; + } + } + if (isCompoundRule) { + // As it's compound rule, Get the Apply types + for (JAXBElement jaxbElement : jaxbDecisionTypes) { + ApplyType innerDecisionApply = (ApplyType) jaxbElement.getValue(); + index = prePopulateDecisionCompoundRuleAlgorithm(index, innerDecisionApply); + } + // Populate combo box + if (logger.isDebugEnabled()) { + logger.debug("Prepopulating Compound rule algorithm: " + index); + } + Map rule = new HashMap(); + for (String key : PolicyController.getDropDownMap().keySet()) { + String keyValue = PolicyController.getDropDownMap().get(key); + if (keyValue.equals(decisionApply.getFunctionId())) { + rule.put("dynamicRuleAlgorithmCombo", key); + } + } + + rule.put("id", "A" + (index +1)); + // Populate Key and values for Compound Rule + rule.put("dynamicRuleAlgorithmField1", "A" + (ruleAlgoirthmTracker.getLast() + 1 )); + ruleAlgoirthmTracker.removeLast(); + rule.put("dynamicRuleAlgorithmField2", "A" + (ruleAlgoirthmTracker.getLast() + 1)); + ruleAlgoirthmTracker.removeLast(); + ruleAlgoirthmTracker.addLast(index); + ruleAlgorithmList.add(rule); + index++; + } + return index; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PDPController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PDPController.java new file mode 100644 index 000000000..add650b1e --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PDPController.java @@ -0,0 +1,302 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.dao.GroupEntityDao; +import org.openecomp.policy.dao.PDPEntityDao; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPGroup; +import org.openecomp.policy.xacml.std.pap.StdPDP; +import org.openecomp.policy.xacml.std.pap.StdPDPGroup; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping({"/"}) +public class PDPController extends RestrictedBaseController { + private static final Logger logger = FlexLogger.getLogger(PDPController.class); + + @Autowired + GroupEntityDao groupDAO; + + @Autowired + PDPEntityDao pdpDAO; + + protected List groups = Collections.synchronizedList(new ArrayList()); + private PDPGroupContainer container; + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + this.groups.addAll(PolicyController.getPapEngine().getEcompPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message); + } + + } + } + + @RequestMapping(value={"/get_PDPGroupContainerData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPDPGroupContainerData(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group Container data" + e); + } + } + + @RequestMapping(value={"/get_PDPGroupData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPDPGroupEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while retrieving the PDP Group data" + e); + } + } + + @RequestMapping(value={"/pdp_Group/save_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString().replace("groupName", "name"), StdPDPGroup.class); + try { + if(pdpGroupData.getId() == null){ + this.container.addNewGroup(pdpGroupData.getName(), pdpGroupData.getDescription()); + }else{ + this.container.updateGroup(pdpGroupData); + } + + } catch (Exception e) { + String message = "Unable to create Group. Reason:\n" + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message); + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + StdPDPGroup pdpGroupData = mapper.readValue(root.get("pdpGroupData").toString(), StdPDPGroup.class); + if(pdpGroupData.getName().equals("Default")) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + }else{ + this.container.removeGroup(pdpGroupData, null); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView savePDPToGroup(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + String update = root.get("update").toString(); + PdpData pdpGroupData = (PdpData)mapper.readValue(root.get("pdpInGroup").toString(), PdpData.class); + StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); + try { + + if(update.contains("false")){ + this.container.addNewPDP(pdpGroupData.getId(), activeGroupData, pdpGroupData.getName(), pdpGroupData.getDescription(), pdpGroupData.getJmxPort()); + }else{ + this.container.updateGroup(activeGroupData); + } + } catch (Exception e) { + String message = "Unable to create Group. Reason:\n" + e.getMessage(); + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message); + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) throws Exception { + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + this.container = new PDPGroupContainer(PolicyController.getPapEngine()); + StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class); + StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); + + this.container.removePDP(deletePdp, activeGroupData); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(); + String responseString = mapper.writeValueAsString(groups); + JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}"); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} + +class PdpData{ + String id; + int jmxPort; + String name; + String description; + public String getId() { + return id; + } + public void setId(String id) { + this.id = id; + } + public int getJmxPort() { + return jmxPort; + } + public void setJmxPort(int jmxPort) { + this.jmxPort = jmxPort; + } + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + public String getDescription() { + return description; + } + public void setDescription(String description) { + this.description = description; + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyController.java new file mode 100644 index 000000000..c4b254c8e --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyController.java @@ -0,0 +1,418 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Properties; + +import javax.annotation.PostConstruct; +import javax.mail.MessagingException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.json.JSONObject; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.dao.FunctionDefinitionDao; +import org.openecomp.policy.dao.PolicyEditorScopesDao; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.dao.RolesDao; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.XacmlAdminAuthorization; +import org.openecomp.policy.rest.dao.UserInfoDao; +import org.openecomp.policy.rest.jpa.Datatype; +import org.openecomp.policy.rest.jpa.FunctionDefinition; +import org.openecomp.policy.rest.jpa.PolicyEditorScopes; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.util.Webapps; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; + +import com.att.research.xacml.api.pap.PAPEngine; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Controller +@RequestMapping("/") +public class PolicyController extends RestrictedBaseController { + private static final Logger LOGGER = FlexLogger.getLogger(PolicyController.class); + private static UserInfoDao userInfoDao; + private static PolicyVersionDao policyVersionDao; + private static RolesDao rolesDao; + private static PolicyEditorScopesDao policyEditorScopesDao; + private static WatchPolicyNotificationDao watchPolicyNotificationDao; + // Our authorization object + // + XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization(); + // + // The PAP Engine + // + private static PAPPolicyEngine papEngine; + private Path repositoryPath = null; + private static Path workspacePath; + private static Path gitPath; + public static String logTableLimit; + public static String systemAlertTableLimit; + public static String CONFIG_HOME = PolicyController.getConfigHome(); + public static String ACTION_HOME = PolicyController.getActionHome(); + protected static Map dropDownMap = new HashMap(); + public static Map getDropDownMap() { + return dropDownMap; + } + + public static void setDropDownMap(Map dropDownMap) { + PolicyController.dropDownMap = dropDownMap; + } + + public static String getDomain() { + return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); + } + + private static final Object mapAccess = new Object(); + private static Map> mapDatatype2Function = null; + private static Map mapID2Function = null; + + private static FunctionDefinitionDao functionDefinitionDao; + + //Smtp Java Mail Properties + public static String smtpHost = null; + public static String smtpPort = null; + public static String smtpUsername = null; + public static String smtpPassword = null; + public static String smtpApplicationName = null; + public static String smtpEmailExtension = null; + //log db Properties + public static String logdbDriver = null; + public static String logdbUrl = null; + public static String logdbUserName = null; + public static String logdbPassword = null; + public static String logdbDialect = null; + + + @Autowired + private PolicyController(UserInfoDao userinfoDao, PolicyVersionDao policyVersionDao, FunctionDefinitionDao functionDefinitionDao, + RolesDao rolesDao, PolicyEditorScopesDao policyEditorScopesDao, WatchPolicyNotificationDao watchPolicyNotificationDao){ + PolicyController.userInfoDao = userinfoDao; + PolicyController.policyVersionDao = policyVersionDao; + PolicyController.functionDefinitionDao = functionDefinitionDao; + PolicyController.rolesDao = rolesDao; + PolicyController.policyEditorScopesDao = policyEditorScopesDao; + PolicyController.watchPolicyNotificationDao = watchPolicyNotificationDao; + } + + public PolicyController() { + } + + @PostConstruct + public void init(){ + Properties prop = new Properties(); + InputStream input = null; + try { + input = new FileInputStream("xacml.admin.properties"); + // load a properties file + prop.load(input); + // get the property values + smtpHost = prop.getProperty("ecomp.smtp.host"); + smtpPort = prop.getProperty("ecomp.smtp.port"); + smtpUsername = prop.getProperty("ecomp.smtp.userName"); + smtpPassword = prop.getProperty("ecomp.smtp.password"); + smtpApplicationName = prop.getProperty("ecomp.application.name"); + smtpEmailExtension = prop.getProperty("ecomp.smtp.emailExtension"); + //Log Database Properties + logdbDriver = prop.getProperty("xacml.log.db.driver"); + logdbUrl = prop.getProperty("xacml.log.db.url"); + logdbUserName = prop.getProperty("xacml.log.db.user"); + logdbPassword = prop.getProperty("xacml.log.db.password"); + logdbDialect = prop.getProperty("ecomp.dialect"); + //Get the Property Values for Dashboard tab Limit + try{ + logTableLimit = prop.getProperty("xacml.ecomp.dashboard.logTableLimit"); + systemAlertTableLimit = prop.getProperty("xacml.ecomp.dashboard.systemAlertTableLimit"); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e); + logTableLimit = "5000"; + systemAlertTableLimit = "2000"; + } + repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY)); + PolicyController.workspacePath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE), getDefaultWorkspace()); + setGitPath(Paths.get(workspacePath.toString(), repositoryPath.getFileName().toString())); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties"); + } catch (IOException ex) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while reading the Smtp properties from xacml.admin.properties file" +ex); + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured while Closing the xacml.admin.properties file" +e); + } + } + } + + //Initialize the FunctionDefinition table at Server Start up + Map> functionMap = getFunctionDatatypeMap(); + for (Datatype id : functionMap.keySet()) { + List functionDefinations = (List) functionMap.get(id); + for (FunctionDefinition functionDef : functionDefinations) { + dropDownMap.put(functionDef.getShortname(),functionDef.getXacmlid()); + } + } + + } + + public static Map> getFunctionDatatypeMap() { + synchronized(mapAccess) { + if (mapDatatype2Function == null) { + buildFunctionMaps(); + } + } + return mapDatatype2Function; + } + + public static Map getFunctionIDMap() { + synchronized(mapAccess) { + if (mapID2Function == null) { + buildFunctionMaps(); + } + } + return mapID2Function; + } + + private static void buildFunctionMaps() { + mapDatatype2Function = new HashMap>(); + mapID2Function = new HashMap(); + List functiondefinitions = functionDefinitionDao.getFunctionDefinition(); + for (int i = 0; i < functiondefinitions.size(); i ++) { + FunctionDefinition value = functiondefinitions.get(i); + mapID2Function.put(value.getXacmlid(), value); + if (mapDatatype2Function.containsKey(value.getDatatypeBean()) == false) { + mapDatatype2Function.put(value.getDatatypeBean(), new ArrayList()); + } + mapDatatype2Function.get(value.getDatatypeBean()).add(value); + } + } + + public static Map getUserRoles(String userId) { + Map scopes = new HashMap(); + List roles = rolesDao.getUserRoles(userId); + if (roles != null && roles.size() > 0) { + for (Roles role : roles) { + scopes.put(role.getScope(), role); + } + } + return scopes; + } + + public static List getRolesOfUser(String userId) { + List rolesList = new ArrayList(); + List roles = rolesDao.getUserRoles(userId); + for (Roles role: roles) { + rolesList.add(role.getRole()); + } + return rolesList; + } + + public static List getRoles(String userId) { + return rolesDao.getUserRoles(userId); + } + + //Get List of User Roles + @RequestMapping(value={"/get_UserRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getUserRolesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + String userId = UserUtils.getUserIdFromCookie(request); + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("userRolesDatas", mapper.writeValueAsString(getRolesOfUser(userId))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + //Policy tabs Model and View + @RequestMapping(value= {"/policy", "/policy/*" }, method = RequestMethod.GET) + public ModelAndView view(HttpServletRequest request){ + String myRequestURL = request.getRequestURL().toString(); + try { + // + // Set the URL for the RESTful PAP Engine + // + setPapEngine((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); + new PDPGroupContainer((PAPPolicyEngine) new RESTfulPAPEngine(myRequestURL)); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e); + } + Map model = new HashMap(); + return new ModelAndView("policy_Editor","model", model); + } + + public static String getDefaultWorkspace() { + return "admin"; + } + + public static PAPPolicyEngine getPapEngine() { + return papEngine; + } + + public void setPapEngine(PAPPolicyEngine papEngine) { + PolicyController.papEngine = papEngine; + } + + //Config and Action Directory's + public static String getConfigHome() { + return Webapps.getConfigHome(); + } + + public static String getActionHome() { + return Webapps.getActionHome(); + } + + public static Path getGitPath() { + return gitPath; + } + + public static void setGitPath(Path gitPath) { + PolicyController.gitPath = gitPath; + } + + public static String getUserName(String createdBy) { + String loginId = createdBy; + return userInfoDao.getUserName(loginId); + } + + public static boolean getActivePolicy(String query) { + if(policyVersionDao.getActiveVersionPolicy(query).size() > 0){ + return true; + }else{ + return false; + } + + } + + //Get the Active Version of Policy List from Policy Version table + public static List getListOfActivePolicies(String query){ + return policyVersionDao.getActiveVersionPolicy(query); + } + + public static void updatePolicyVersion(String query) { + policyVersionDao.updateQuery(query); + } + + public static void SaveToPolicyVersion(PolicyVersion policyversion) { + policyVersionDao.Save(policyversion); + } + + public static PolicyVersion getPolicyEntityFromPolicyVersion(String query){ + PolicyVersion policyVersionEntity = policyVersionDao.getPolicyVersionEntityByName(query).get(0); + return policyVersionEntity; + } + + public static void SavePolicyScope(PolicyEditorScopes policyScope){ + policyEditorScopesDao.Save(policyScope); + } + + public static List getListOfPolicyEditorScopes(String query){ + return policyEditorScopesDao.getListOfPolicyScopes(query); + } + + public static void updatePolicyScopeEditorWithQuery(String policyScopeQuery) { + policyEditorScopesDao.updateQuery(policyScopeQuery); + + } + + public static void updatePolicyScopeEditor(PolicyEditorScopes policyScopeQuery) { + policyEditorScopesDao.update(policyScopeQuery); + + } + + public void WatchPolicyFunction(PolicyVersion entity, String policyName, String mode){ + PolicyNotificationMail email = new PolicyNotificationMail(); + try { + email.sendMail(entity, policyName, mode, watchPolicyNotificationDao); + } catch (MessagingException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e); + } + } + + //Switch Version + public JSONObject SwitchVersionPolicyContent(File policyFile) { + Path parent = Paths.get(policyFile.toString().substring(0, policyFile.toString().lastIndexOf(File.separator))); + String policyName = policyFile.toString().substring(policyFile.toString().indexOf("repository") +11); + String removeExtension = policyName.replace(".xml", ""); + String activeVersion = removeExtension.substring(removeExtension.lastIndexOf(".")+1); + String dbPolicyName = removeExtension.substring(0, removeExtension.lastIndexOf(".")); + String filterPolicyName = dbPolicyName.substring(dbPolicyName.lastIndexOf(File.separator)+1); + FileFilter fileFilter = new WildcardFileFilter(filterPolicyName + "." + "*" + ".xml"); + File[] files = ((File) parent.toFile()).listFiles(fileFilter); + List av = new ArrayList(); + for(File file : files){ + String fileName = file.toString().substring(file.toString().indexOf("repository") +11); + String removeXMLExtension = fileName.replace(".xml", ""); + String availableVersion = removeXMLExtension.substring(removeXMLExtension.lastIndexOf(".")+1); + av.add(availableVersion); + } + PolicyVersion entity = (PolicyVersion) policyVersionDao.getPolicyVersionEntityByName(dbPolicyName).get(0); + String highestVersion = Integer.toString(entity.getHigherVersion()); + JSONObject el = new JSONObject(); + el.put("activeVersion", activeVersion); + el.put("availableVersions", av); + el.put("highestVersion", highestVersion); + return el; + } + + public static Path getUserWorkspace() { + return PolicyController.workspacePath; + } + +} + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java new file mode 100644 index 000000000..76fadb59d --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java @@ -0,0 +1,563 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.ServletContext; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyExportAdapter; +import org.openecomp.policy.dao.PolicyVersionDao; +import org.openecomp.policy.elk.client.ElkConnector; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.utils.XACMLPolicyWriterWithPapNotify; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Controller +@RequestMapping("/") +public class PolicyExportAndImportController extends RestrictedBaseController { + private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class); + private ArrayList selectedPolicy; + public static String CONFIG_HOME = PolicyController.getConfigHome(); + public static String ACTION_HOME = PolicyController.getActionHome(); + + private Set scopes = null; + private List roles = null; + private Boolean superadmin = false; + private Boolean showMessage = false; + private static final int BUFFER_SIZE = 4096; + private Path directory = PolicyController.getGitPath(); + + //Scopes Which Super Editor can't import + private Set sEditorScopesCantCreate = new HashSet(); + //List of scopes in Tar file + private Set listOfTarNewScopes = new HashSet(); + //List of xml policies + private ArrayList xacmlFiles = new ArrayList(); + //Scopes of the User based on the Roles + private List userScopes = null; + //Directory names from tar file + private Set directoryNames = new HashSet(); + //compare the scopes of the user and tar file get unique + private Set finalScopesToImport = new HashSet(); + //final scopes User can import + private Set finalScopes = new HashSet(); + //User don't have permissions to import to scopes + private Set roleIsNotSufficient = new HashSet(); + //User don't have access to import new scopes + private Set userDontHavePermission = new HashSet(); + + private Map scopeAndRoles = null; + + private static PolicyVersionDao policyVersionDao; + + @Autowired + ServletContext servletContext; + + @Autowired + private PolicyExportAndImportController(PolicyVersionDao policyVersionDao){ + PolicyExportAndImportController.policyVersionDao = policyVersionDao; + } + + public PolicyExportAndImportController(){} + + @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView ExportPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try{ + selectedPolicy = new ArrayList(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyExportAdapter adapter = mapper.readValue(root.get("exportData").toString(), PolicyExportAdapter.class); + for (Object policyId : adapter.getPolicyDatas()) { + LinkedHashMap selected = (LinkedHashMap)policyId; + Path file = Paths.get(selected.get("filePath").toString()); + selectedPolicy.add(file.toFile()); + } + // Grab our working repository + // + final Path repoPath = PolicyController.getGitPath().toAbsolutePath(); + if(CONFIG_HOME == null || ACTION_HOME == null ){ + CONFIG_HOME = PolicyController.getConfigHome(); + ACTION_HOME = PolicyController.getActionHome(); + } + Path configPath = Paths.get(CONFIG_HOME); + Path actionPath = Paths.get(ACTION_HOME); + String tempDir = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp"; + File temPath = new File(tempDir); + if(!temPath.exists()){ + temPath.mkdir(); + } + final Path tarFile = Paths.get(tempDir, "Repository.tar"); + try (OutputStream os = Files.newOutputStream(tarFile)) { + try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(os)) { + tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); + Files.walkFileTree(configPath, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + for (File policyId : selectedPolicy) { + // Get the current selection + String policyDir = policyId.toString(); + policyDir = policyDir.substring(policyDir.indexOf("repository")+11); + String path = policyDir.replace('\\', '.'); + if(path.contains("/")){ + path = policyDir.replace('/', '.'); + logger.info("print the path:" +path); + } + path = FilenameUtils.removeExtension(path); + if (path.endsWith(".xml")) { + path = path.substring(0, path.length() - 4); + } + File configFile = new File(path); + String fileName = FilenameUtils.removeExtension(file.getFileName().toString()); + File configHome = new File(fileName); + if(configFile.equals(configHome)) { + Path relative = configPath.relativize(file); + TarArchiveEntry entry = new TarArchiveEntry(relative.toFile()); + entry.setSize(Files.size(file)); + tarOut.putArchiveEntry(entry); + try { + IOUtils.copy(Files.newInputStream(file), tarOut); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + tarOut.closeArchiveEntry(); + return super.visitFile(file, attrs); + } + } + return super.visitFile(file, attrs); + } + }); + + Files.walkFileTree(actionPath, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + for (File policyId : selectedPolicy) { + // Get the current selection + String policyDir = policyId.toString(); + policyDir = policyDir.substring(policyDir.indexOf("repository")+11); + String path = policyDir.replace('\\', '.'); + if(path.contains("/")){ + path = policyDir.replace('/', '.'); + logger.info("print the path:" +path); + } + path = FilenameUtils.removeExtension(path); + if (path.endsWith(".xml")) { + path = path.substring(0, path.length() - 4); + } + File actionFile = new File(path); + String fileName = FilenameUtils.removeExtension(file.getFileName().toString()); + File actionHome = new File(fileName); + if(actionFile.equals(actionHome)) { + Path relative = actionPath.relativize(file); + TarArchiveEntry entry = new TarArchiveEntry(relative.toFile()); + entry.setSize(Files.size(file)); + tarOut.putArchiveEntry(entry); + try { + IOUtils.copy(Files.newInputStream(file), tarOut); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + tarOut.closeArchiveEntry(); + return super.visitFile(file, attrs); + } + } + return super.visitFile(file, attrs); + } + }); + + Files.walkFileTree(repoPath, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (file.getFileName().toString().endsWith(".xml") == false) { + return super.visitFile(file, attrs); + } + for (File policyId : selectedPolicy) { + // Get the current selection + if(policyId.getAbsoluteFile().getName().equals(file.getFileName().toString())) { + Path relative = repoPath.relativize(file); + TarArchiveEntry entry = new TarArchiveEntry(relative.toFile()); + entry.setSize(Files.size(file)); + tarOut.putArchiveEntry(entry); + try { + IOUtils.copy(Files.newInputStream(file), tarOut); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + tarOut.closeArchiveEntry(); + return super.visitFile(file, attrs); + } + } + return super.visitFile(file, attrs); + } + }); + + tarOut.closeArchiveEntry(); + tarOut.finish(); + logger.debug("closing the tar file"); + } + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "getting IOexception"); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + logger.info("trying to send tar file "+tarFile.toAbsolutePath().toString()); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + String successMap = tarFile.toString().substring(tarFile.toString().lastIndexOf("webapps")+8); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{data: " + responseString + "}"); + out.write(j.toString()); + + + return null; + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e); + } + return null; + } + + //Policy Import + public JSONObject ImportRepositoryFile(String file, HttpServletRequest request){ + TarArchiveEntry entry = null; + TarArchiveInputStream extractFile = null; + try { + extractFile = new TarArchiveInputStream (new FileInputStream(file)); + } catch (FileNotFoundException e1) { + e1.printStackTrace(); + } + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + logger.error("Exception Occured while reading userid from cookie" +e); + } + scopeAndRoles = PolicyController.getUserRoles(userId); + //Check if the Role and Scope Size are Null get the values from db. + List userRoles = PolicyController.getRoles(userId); + roles = new ArrayList(); + scopes = new HashSet(); + for(Roles userRole: userRoles){ + roles.add(userRole.getRole()); + scopes.add(userRole.getScope()); + } + //Create a loop to read every single entry in TAR file + try { + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) { + while ((entry = extractFile.getNextTarEntry()) != null) { + this.superadmin = true; + try{ + copyFileToLocation(extractFile, entry, xacmlFiles, null, superadmin); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception while Importing Polcies"+e); + } + } + }else{ + this.showMessage = true; + //get the directory names from tar file and add to the list + while ((entry = extractFile.getNextTarEntry()) != null) { + if(entry.getName().endsWith(".xls")) { + this.superadmin = true; + try{ + copyFileToLocation(extractFile, entry, xacmlFiles, finalScopes, superadmin); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception while Importing Polcies"+e); + } + } + if(entry.getName().endsWith(".xml")){ + String filename = null; + if(entry.getName().contains("\\")){ + filename = entry.getName().replace("\\", File.separator); + }else{ + filename = entry.getName().replace("/", File.separator); + } + directoryNames.add(filename.substring(0, filename.lastIndexOf(File.separator))); + } + + //get the matching scopes on comparing user scopes and tar file scopes + for(int i=0;i< userScopes.size(); i++){ + for(int j=0; j xacmlFiles, Set finalScopes, Boolean superadminValue ) throws IOException{ + String individualFiles = ""; + int offset = 0; + FileOutputStream outputFile=null; + // Get the name of the file + if(superadminValue){ + individualFiles = entry.getName(); + //Add the list of scopes + if(entry.getName().endsWith(".xml")){ + String filename = null; + if(entry.getName().contains("\\")){ + filename = entry.getName().replace("\\", File.separator); + }else{ + filename = entry.getName().replace("/", File.separator); + } + if(roles.contains("super-editor")){ + listOfTarNewScopes.add(filename.substring(0, filename.lastIndexOf(File.separator))); + } + } + }else{ + for(int i =0; i< finalScopes.size(); i++){ + if(entry.getName().startsWith(finalScopes.toArray()[i].toString())){ + individualFiles = entry.getName(); + } + } + } + + //Filter the new Scopes which Super-Editor can't create + if(roles.contains("super-editor")){ + for(int j= 0; j< listOfTarNewScopes.size(); j++){ + boolean scopeExistsFlag = false; // This Flag is used to know if the Scope Exists. + for(int i=0; i < scopes.size(); i++ ){ + if(scopes.contains(listOfTarNewScopes.toArray()[j])){ + scopeExistsFlag = true; + } + } + if(!scopeExistsFlag){ + sEditorScopesCantCreate.add(listOfTarNewScopes.toArray()[j].toString()); + showMessage = true; + } + } + } + + individualFiles = individualFiles.replace("/", File.separator); + individualFiles = individualFiles.replace("\\", File.separator); + + //Create the path with the entry name + String filePath = directory + File.separator + individualFiles; + String configPath = CONFIG_HOME + File.separator + individualFiles; + String actionPath = ACTION_HOME + File.separator + individualFiles; + logger.info("File Name in TAR File is: " + individualFiles); + logger.info("Xml directory file path: " + filePath); + logger.info("Config Home directory file path: " + configPath); + logger.info("Action Home directory file path: " + actionPath); + + + // Get Size of the file and create a byte array for the size + byte[] content = new byte[(int) entry.getSize()]; + + offset=0; + logger.info("File Name in TAR File is: " + individualFiles); + logger.info("Size of the File is: " + entry.getSize()); + // Read file from the archive into byte array + extractFile.read(content, offset, content.length - offset); + if (!entry.isDirectory()) { + if(!individualFiles.contains(".Config_") || !individualFiles.contains(".Action_")){ + // if the entry is a file, extracts it + String filePath1 = filePath.substring(0, filePath.lastIndexOf(File.separator)); + File newFile = new File(filePath1); + if(!(newFile.exists()) && !(roles.contains("super-editor") || roles.contains("editor"))) { + File dir = new File(filePath1); + dir.mkdir(); + extractFile(extractFile, filePath); + } + } + } else { + // if the entry is a directory, make the directory + if(!(roles.contains("super-editor") || roles.contains("editor"))){ + File dir = new File(filePath); + dir.mkdir(); + } + } + // Define OutputStream for writing the file + if(individualFiles.contains(".Config_")){ + outputFile=new FileOutputStream(new File(configPath)); + }else if(individualFiles.contains(".Action_")){ + outputFile=new FileOutputStream(new File(actionPath)); + }else{ + if(filePath != null){ + outputFile=new FileOutputStream(new File(filePath)); + xacmlFiles.add(filePath); + } + } + + // Use IOUtiles to write content of byte array to physical file + IOUtils.write(content,outputFile); + + // Close Output Stream + try { + outputFile.close(); + } catch (IOException e) { + logger.info("IOException:" +e); + e.printStackTrace(); + } + } + + private void extractFile(TarArchiveInputStream extractFile, String filePath) throws IOException { + BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath)); + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = extractFile.read(bytesIn)) != -1) { + bos.write(bytesIn, 0, read); + } + bos.close(); + + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java new file mode 100644 index 000000000..203f3dcc6 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +/* + * + * */ +import java.io.File; +import java.io.PrintWriter; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; + +@Controller +@RequestMapping({"/"}) +public class PolicyNotificationController extends RestrictedBaseController { + + @Autowired + WatchPolicyNotificationDao policyNotificationDao; + + @RequestMapping(value={"/watchPolicy"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView watchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String path = ""; + String responseValue = ""; + try { + String userId = UserUtils.getUserIdFromCookie(request); + System.out.println(userId); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + String name = root.get("watchData").get("name").toString(); + JsonNode pathList = root.get("watchData").get("path"); + String finalName = ""; + if(pathList.isArray()){ + ArrayNode arrayNode = (ArrayNode) pathList; + for (int i = 0; i < arrayNode.size(); i++) { + JsonNode individualElement = arrayNode.get(i); + if(i == 0){ + path = path + individualElement.toString().replace("\"", "").trim(); + }else{ + path = path + File.separator + individualElement.toString().replace("\"", "").trim(); + } + } + } + + if(pathList.size() > 0){ + finalName = path + File.separator + name.replace("\"", "").trim(); + }else{ + finalName = name.replace("\"", "").trim(); + } + if(finalName.contains("\\")){ + finalName = finalName.replace("\\", "\\\\"); + } + String query = "from WatchPolicyNotificationTable where POLICYNAME = '"+finalName+"' and LOGINIDS = '"+userId+"'"; + List watchList = policyNotificationDao.watchListQuery(query); + if(watchList.isEmpty()){ + if(finalName.contains("\\\\")){ + finalName = finalName.replace("\\\\", File.separator); + } + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + watch.setPolicyName(finalName); + watch.setLoginIds(userId); + policyNotificationDao.save(watch); + responseValue = "You have Subscribed Successfully"; + }else{ + policyNotificationDao.delete(watchList.get(0)); + responseValue = "You have UnSubscribed Successfully"; + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(responseValue); + JSONObject j = new JSONObject("{watchData: " + responseString + "}"); + out.write(j.toString()); + return null; + }catch(Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java new file mode 100644 index 000000000..dea341ea9 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java @@ -0,0 +1,137 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.File; +import java.io.PrintWriter; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.dao.PolicyRolesDao; +import org.openecomp.policy.rest.jpa.PolicyRoles; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class PolicyRolesController extends RestrictedBaseController{ + + @Autowired + PolicyRolesDao policyRolesDao; + List scopelist; + + @RequestMapping(value={"/get_RolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyRolesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("rolesDatas", mapper.writeValueAsString(policyRolesDao.getUserRoles())); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @RequestMapping(value={"/save_NonSuperRolesData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView SaveRolesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyRoles adapter = mapper.readValue(root.get("editRoleData").toString(), PolicyRoles.class); + policyRolesDao.update(adapter); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(policyRolesDao.getUserRoles()); + JSONObject j = new JSONObject("{rolesDatas: " + responseString + "}"); + + out.write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + return null; + } + + @RequestMapping(value={"/get_PolicyRolesScopeData"}, method={org.springframework.web.bind.annotation.RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) + public void getPolicyScopesEntityData(HttpServletRequest request, HttpServletResponse response){ + try{ + scopelist = new ArrayList(); + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); + Path gitPath = PolicyController.getGitPath().toAbsolutePath(); + model.put("scopeDatas", mapper.writeValueAsString(readFileRepository(gitPath))); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + public List readFileRepository(Path path){ + File root = new File(path.toString()); + for ( File file : root.listFiles()){ + if(file.isDirectory()){ + String fileName = getDomain(file); + if (!(fileName.contains(".git") || fileName.equals(".DS_Store"))) { + scopelist.add(fileName); + } + readFileRepository(file.toPath()); + } + } + return scopelist; + } + + public String getDomain(File file) { + String filePath = file.getAbsolutePath(); + int startIndex = filePath.indexOf("repository") + 11; + return filePath.substring(startIndex, filePath.length()); + } + +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java new file mode 100644 index 000000000..5ffdd062a --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java @@ -0,0 +1,300 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.controller; + + +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.adapter.ClosedLoopFaultBody; +import org.openecomp.policy.adapter.ClosedLoopPMBody; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.admin.RESTfulPAPEngine; +import org.openecomp.policy.rest.dao.SafePolicyWarningDao; +import org.openecomp.policy.rest.jpa.SafePolicyWarning; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.servlet.ModelAndView; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.CharMatcher; + +@Controller +@RequestMapping("/") +public class PolicyValidationController extends RestrictedBaseController { + + public static final String CONFIG_POLICY = "Config"; + public static final String ACTION_POLICY = "Action"; + public static final String DECISION_POLICY = "Decision"; + public static final String CLOSEDLOOP_POLICY = "ClosedLoop_Fault"; + public static final String CLOSEDLOOP_PM = "ClosedLoop_PM"; + public static final String ENFORCER_CONFIG_POLICY= "Enforcer Config"; + public static final String MICROSERVICES="DCAE Micro Service"; + private Pattern pattern; + private Matcher matcher; + + private static final String EMAIL_PATTERN = + "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; + + @Autowired + SafePolicyWarningDao safePolicyWarningDao; + + @RequestMapping(value={"/policyController/validate_policy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView validatePolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try{ + boolean valid = true; + String responseString = ""; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyAdapter policyData = (PolicyAdapter)mapper.readValue(root.get("policyData").toString(), PolicyAdapter.class); + if(policyData.getPolicyName() != null){ + String policyNameValidate = emptyValidator(policyData.getPolicyName()); + if(!policyNameValidate.contains("success")){ + responseString = responseString + "PolicyName:" + policyNameValidate; + valid = false; + }; + }else{ + responseString = responseString + "PolicyName: PolicyName Should not be empty" + "
"; + } + if(policyData.getPolicyDescription() != null){ + String descriptionValidate = descriptionValidator(policyData.getPolicyDescription()); + if(!descriptionValidate.contains("success")){ + responseString = responseString + "Description:" + descriptionValidate; + valid = false; + } + } + + if(policyData.getPolicyType().equals(CONFIG_POLICY)){ + if (policyData.getConfigPolicyType().equals("Base") || policyData.getConfigPolicyType().equals(CLOSEDLOOP_POLICY) + || policyData.getConfigPolicyType().equals(CLOSEDLOOP_PM) || policyData.getConfigPolicyType().equals(ENFORCER_CONFIG_POLICY) || policyData.getConfigPolicyType().equals(MICROSERVICES)) { + if(policyData.getEcompName() != null){ + String ecompNameValidate = emptyValidator(policyData.getEcompName()); + if(!ecompNameValidate.contains("success")){ + responseString = responseString + "EcompName:" + ecompNameValidate; + valid = false; + } + }else{ + responseString = responseString + "Ecomp Name: Ecomp Name Should not be empty" + "
"; + } + } + + if(policyData.getRiskType() != null){ + String riskTypeValidate = emptyValidator(policyData.getRiskType()); + if(!riskTypeValidate.contains("success")){ + responseString = responseString + "RiskType:" + riskTypeValidate; + valid = false; + }else { + SafePolicyWarning safePolicyWarningData = safePolicyWarningDao.getSafePolicyWarningDataById(policyData.getRiskType()); + if (safePolicyWarningData!=null){ + safePolicyWarningData.getMessage(); + responseString = responseString + "Messaage:" + safePolicyWarningData.getMessage(); + } + } + }else { + responseString = responseString + "Risk Type: Risk Type Should not be Empty" + "
"; + valid = false; + } + + if(policyData.getRiskLevel() != null){ + String validateRiskLevel = emptyValidator(policyData.getRiskLevel()); + if(!validateRiskLevel.contains("success")){ + responseString = responseString + "RiskLevel:" + validateRiskLevel; + valid = false; + } + }else { + responseString = responseString + "Risk Level: Risk Level Should not be Empty" + "
"; + valid = false; + } + + if(policyData.getGuard() != null){ + String validateGuard = emptyValidator(policyData.getGuard()); + if(!validateGuard.contains("success")){ + responseString = responseString + "Guard:" + validateGuard; + valid = false; + } + }else { + responseString = responseString + "Guard: Guard Value Should not be Empty" + "
"; + valid = false; + } + + if(policyData.getConfigPolicyType().equals("Base")){ + if(policyData.getConfigName() != null){ + String configNameValidate = emptyValidator(policyData.getConfigName()); + if(!configNameValidate.contains("success")){ + responseString = responseString + "ConfigName:" + configNameValidate; + valid = false; + } + }else{ + responseString = responseString + "Config Name: Config Name Should not be Empty" + "
"; + } + if(policyData.getConfigType() != null){ + String configTypeValidate = emptyValidator(policyData.getConfigType()); + if(!configTypeValidate.contains("success")){ + responseString = responseString + "ConfigType:" + configTypeValidate; + valid = false; + } + }else{ + responseString = responseString + "Config Type: Config Type Should not be Empty" + "
"; + } + if(policyData.getConfigBodyData() != null){ + String policyType = policyData.getPolicyType(); + RESTfulPAPEngine engine = (RESTfulPAPEngine) PolicyController.getPapEngine(); + if(!engine.validatePolicyRequest(policyData, policyType)){ + responseString = responseString + "ConfigBody: Validation Failed"; + valid = false; + } + }else{ + responseString = responseString + "Config Body: Config Body Should not be Empty" + "
"; + } + } + + + if(policyData.getJsonBodyData() != null){ + if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){ + ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class); + if(pmBody.getEmailAddress() != null){ + String validateEmail = validateEmailAddress(pmBody.getEmailAddress().toString()); + if(!validateEmail.contains("success")){ + responseString = responseString + "Email:" + validateEmail; + valid = false; + } + }else{ + valid = true; + } + }else if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){ + ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); + if(faultBody.getEmailAddress() != null){ + String validateEmail = validateEmailAddress(faultBody.getEmailAddress().toString()); + if(!validateEmail.contains("success")){ + responseString = responseString + "Email:" + validateEmail; + valid = false; + } + }else{ + valid = true; + } + } + } + } + if (policyData.getPolicyType().equals(DECISION_POLICY)){ + String ecompNameValidate = emptyValidator(policyData.getEcompName()); + if(!ecompNameValidate.contains("success")){ + responseString = responseString + "EcompName:" + ecompNameValidate; + valid = false; + } + } + + if(policyData.getPolicyType().equals(ACTION_POLICY)){ + String actionPerformer = emptyValidator(policyData.getActionPerformer()); + String actionAttribute = emptyValidator(policyData.getActionAttributeValue()); + if(!actionPerformer.contains("success")){ + responseString = responseString + "ActionPerformer:" + actionPerformer; + valid = false; + }; + if(!actionAttribute.contains("success")){ + responseString = responseString + "ActionAttribute:" + actionAttribute; + valid = false; + }; + } + + if(policyData.getPolicyType().equals(CONFIG_POLICY)){ + if(valid){ + responseString = "success" + "@#"+ responseString; + } + }else{ + if(valid){ + responseString = "success"; + } + } + + PrintWriter out = response.getWriter(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + PrintWriter out = response.getWriter(); + out.write(e.getMessage()); + } + return null; + } + + protected String emptyValidator(String field){ + String error = "success"; + if (field.equals("") || field.contains(" ") || !field.matches("^[a-zA-Z0-9_]*$")) { + error = "The Value in Required Field will allow only '{0-9}, {a-z}, {A-Z}, _' following set of Combinations"; + return error; + } else { + if(CharMatcher.ASCII.matchesAllOf((CharSequence) field)){ + error = "success"; + }else{ + error = "The Value Contains Non ASCII Characters"; + return error; + } + } + return error; + } + + protected String descriptionValidator(String field) { + String error = "success"; + if (field.contains("@CreatedBy:") || field.contains("@ModifiedBy:")) { + error = "The value in the description shouldn't contain @CreatedBy: or @ModifiedBy:"; + return error; + } else { + error = "success"; + } + return error; + } + + public String validateEmailAddress(String emailAddressValue) { + String error = "success"; + List emailList = Arrays.asList(emailAddressValue.toString().split(",")); + for(int i =0 ; i < emailList.size() ; i++){ + pattern = Pattern.compile(EMAIL_PATTERN); + matcher = pattern.matcher(emailList.get(i).trim()); + if(!matcher.matches()){ + error = "Please check the Following Email Address is not Valid .... " +emailList.get(i).toString(); + return error; + }else{ + error = "success"; + } + } + return error; + } + +} -- cgit 1.2.3-korg