From e0addf5b588a1244f9679becd90999dfcb4c3a94 Mon Sep 17 00:00:00 2001 From: "ITSERVICES\\rb7147" Date: Tue, 25 Apr 2017 11:46:00 -0400 Subject: Policy 1707 commit to LF Change-Id: Ibe6f01d92f9a434c040abb05d5386e89d675ae65 Signed-off-by: ITSERVICES\rb7147 --- .../java/org/openecomp/policy/admin/CheckPDP.java | 187 +++ .../org/openecomp/policy/admin/PolicyAdapter.java | 112 ++ .../policy/admin/PolicyManagerServlet.java | 1265 ++++++++++++++++++++ .../policy/admin/PolicyNotificationMail.java | 166 +++ .../policy/admin/PolicyRestController.java | 379 ++++++ .../policy/admin/PolicyUserInfoController.java | 58 + .../openecomp/policy/admin/RESTfulPAPEngine.java | 528 ++++++++ .../policy/components/HumanPolicyComponent.java | 982 +++++++++++++++ .../policy/components/PolicyImportWindow.java | 167 +++ .../openecomp/policy/conf/HibernateSession.java | 60 + .../policy/controller/ActionPolicyController.java | 266 ++++ .../policy/controller/AdminTabController.java | 100 ++ .../policy/controller/AutoPushController.java | 355 ++++++ .../controller/CreateBRMSParamController.java | 508 ++++++++ .../policy/controller/CreateBRMSRawController.java | 173 +++ .../CreateClosedLoopFaultController.java | 696 +++++++++++ .../controller/CreateClosedLoopPMController.java | 206 ++++ .../CreateDcaeMicroServiceController.java | 1139 ++++++++++++++++++ .../controller/CreateFirewallController.java | 932 ++++++++++++++ .../policy/controller/CreatePolicyController.java | 165 +++ .../policy/controller/DashboardController.java | 420 +++++++ .../controller/DecisionPolicyController.java | 262 ++++ .../openecomp/policy/controller/PDPController.java | 292 +++++ .../policy/controller/PolicyController.java | 421 +++++++ .../PolicyExportAndImportController.java | 367 ++++++ .../controller/PolicyNotificationController.java | 122 ++ .../policy/controller/PolicyRolesController.java | 163 +++ .../controller/PolicyValidationController.java | 661 ++++++++++ .../org/openecomp/policy/dao/SystemLogDbDao.java | 33 + .../policy/daoImp/CommonClassDaoImpl.java | 385 ++++++ .../policy/daoImp/SystemLogDbDaoImpl.java | 93 ++ .../openecomp/policy/model/PDPGroupContainer.java | 528 ++++++++ .../openecomp/policy/model/PDPPolicyContainer.java | 348 ++++++ .../java/org/openecomp/policy/model/Roles.java | 99 ++ .../policy/utils/ConfigurableRESTUtils.java | 163 +++ .../openecomp/policy/utils/PolicyContainer.java | 121 ++ .../policy/utils/PolicyItemSetChangeNotifier.java | 95 ++ .../utils/XACMLPolicyWriterWithPapNotify.java | 483 ++++++++ 38 files changed, 13500 insertions(+) create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyAdapter.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyUserInfoController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/Roles.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyContainer.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java create mode 100644 POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java (limited to 'POLICY-SDK-APP/src/main/java') diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java new file mode 100644 index 000000000..4f026ff10 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/CheckPDP.java @@ -0,0 +1,187 @@ +/*- + * ============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.admin; + + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +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.Base64; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; + +import org.openecomp.policy.rest.XACMLRestProperties; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.util.XACMLProperties; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +public class CheckPDP { + private static Path pdpPath = null; + private static Properties pdpProp = null; + private static Long oldModified = null; + private static Long newModified = null; + private static HashMap pdpMap = null; + private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class); + + public static boolean validateID(String id) { + // ReadFile + try { + readFile(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + return false; + } + // Check ID + if (pdpMap.containsKey(id)) { + return true; + } + return false; + } + + private static void readFile() throws Exception { + String pdpFile = null; + try{ + pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File"); + return; + } + if (pdpFile == null) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile); + } + if (pdpPath == null) { + pdpPath = Paths.get(pdpFile); + if (Files.notExists(pdpPath)) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString()); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString()); + } + if (pdpPath.toString().endsWith(".properties")) { + readProps(); + } else { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + pdpFile); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file"); + } + } + // Check if File is updated recently + else { + newModified = pdpPath.toFile().lastModified(); + if (newModified != oldModified) { + // File has been updated. + readProps(); + } + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void readProps() throws Exception { + InputStream in; + pdpProp = new Properties(); + try { + in = new FileInputStream(pdpPath.toFile()); + oldModified = pdpPath.toFile().lastModified(); + pdpProp.load(in); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + throw new Exception("Cannot Load the Properties file", e); + } + // Read the Properties and Load the PDPs and encoding. + pdpMap = new HashMap(); + // Check the Keys for PDP_URLs + Collection unsorted = pdpProp.keySet(); + List sorted = new ArrayList(unsorted); + Collections.sort(sorted); + for (String propKey : sorted) { + if (propKey.startsWith("PDP_URL")) { + String check_val = pdpProp.getProperty(propKey); + if (check_val == null) { + throw new Exception("Properties file doesn't have the PDP_URL parameter"); + } + if (check_val.contains(";")) { + List pdp_default = new ArrayList(Arrays.asList(check_val.split("\\s*;\\s*"))); + int pdpCount = 0; + while (pdpCount < pdp_default.size()) { + String pdpVal = pdp_default.get(pdpCount); + readPDPParam(pdpVal); + pdpCount++; + } + } else { + readPDPParam(check_val); + } + } + } + if (pdpMap == null || pdpMap.isEmpty()) { + LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs"); + } + } + + private static void readPDPParam(String pdpVal) throws Exception{ + if(pdpVal.contains(",")){ + List pdpValues = new ArrayList(Arrays.asList(pdpVal.split("\\s*,\\s*"))); + if(pdpValues.size()==3){ + // 1:2 will be UserID:Password + String userID = pdpValues.get(1); + String pass = pdpValues.get(2); + Base64.Encoder encoder = Base64.getEncoder(); + // 0 - PDPURL + pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); + }else{ + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues); + throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); + } + }else{ + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); + throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request."); + } + } + + public static String getEncoding(String pdpID){ + try { + readFile(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + String encoding = null; + if(pdpMap!=null && (!pdpMap.isEmpty())){ + try{ + encoding = pdpMap.get(pdpID); + } catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + return encoding; + }else{ + return null; + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyAdapter.java new file mode 100644 index 000000000..329e3bd29 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyAdapter.java @@ -0,0 +1,112 @@ +package org.openecomp.policy.admin; + +import org.openecomp.policy.controller.ActionPolicyController; +import org.openecomp.policy.controller.CreateBRMSParamController; +import org.openecomp.policy.controller.CreateBRMSRawController; +import org.openecomp.policy.controller.CreateClosedLoopFaultController; +import org.openecomp.policy.controller.CreateClosedLoopPMController; +import org.openecomp.policy.controller.CreateDcaeMicroServiceController; +import org.openecomp.policy.controller.CreateFirewallController; +import org.openecomp.policy.controller.CreatePolicyController; +import org.openecomp.policy.controller.DecisionPolicyController; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.PolicyEntity; + +import com.att.research.xacml.util.XACMLProperties; + +public class PolicyAdapter { + + public void configure(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + String policyNameValue = null ; + String configPolicyName = null ; + if(extendedOptions(policyAdapter, entity)){ + return; + } + if(policyAdapter.getPolicyName().startsWith("Config_PM")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "ClosedLoop_PM"; + }else if(policyAdapter.getPolicyName().startsWith("Config_Fault")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "ClosedLoop_Fault"; + }else if(policyAdapter.getPolicyName().startsWith("Config_FW")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "Firewall Config"; + }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Raw")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "BRMS_Raw"; + }else if(policyAdapter.getPolicyName().startsWith("Config_BRMS_Param")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "BRMS_Param"; + }else if(policyAdapter.getPolicyName().startsWith("Config_MS")){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "Micro Service"; + }else if(policyAdapter.getPolicyName().startsWith("Action") || policyAdapter.getPolicyName().startsWith("Decision") ){ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + }else{ + policyNameValue = policyAdapter.getPolicyName().substring(0, policyAdapter.getPolicyName().indexOf("_")); + configPolicyName = "Base"; + } + if (policyNameValue != null) { + policyAdapter.setPolicyType(policyNameValue); + } + if (configPolicyName != null) { + policyAdapter.setConfigPolicyType(configPolicyName); + } + + if("Action".equalsIgnoreCase(policyAdapter.getPolicyType())){ + ActionPolicyController actionController = new ActionPolicyController(); + actionController.prePopulateActionPolicyData(policyAdapter, entity); + } + if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){ + DecisionPolicyController decisionController = new DecisionPolicyController(); + decisionController.prePopulateDecisionPolicyData(policyAdapter, entity); + } + if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){ + if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreatePolicyController baseController = new CreatePolicyController(); + baseController.prePopulateBaseConfigPolicyData(policyAdapter, entity); + } + else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateBRMSRawController brmsController = new CreateBRMSRawController(); + brmsController.prePopulateBRMSRawPolicyData(policyAdapter, entity); + } + else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateBRMSParamController paramController = new CreateBRMSParamController(); + paramController.prePopulateBRMSParamPolicyData(policyAdapter, entity); + } + else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateClosedLoopFaultController newFaultTemplate = new CreateClosedLoopFaultController(); + newFaultTemplate.prePopulateClosedLoopFaultPolicyData(policyAdapter, entity); + } + else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateClosedLoopPMController pmController = new CreateClosedLoopPMController(); + pmController.prePopulateClosedLoopPMPolicyData(policyAdapter, entity); + } + else if("Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); + msController.prePopulateDCAEMSPolicyData(policyAdapter, entity); + } + else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateFirewallController firewallController = new CreateFirewallController(); + firewallController.prePopulateFWPolicyData(policyAdapter, entity); + } + } + } + + public boolean extendedOptions(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + return false; + } + + public static PolicyAdapter getInstance() { + try { + Class policyAdapter = Class.forName(XACMLProperties.getProperty("policyAdapter.impl.className", PolicyAdapter.class.getName())); + return (PolicyAdapter) policyAdapter.newInstance(); + } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException e) { + e.printStackTrace(); + } + return null; + } + + + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java new file mode 100644 index 000000000..86210cdef --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java @@ -0,0 +1,1265 @@ +/*- + * ============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.admin; + +import java.io.BufferedReader; +import java.io.BufferedWriter; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.FileWriter; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +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.List; +import java.util.Map; +import java.util.Set; + +import javax.json.Json; +import javax.json.JsonArray; +import javax.json.JsonReader; +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebInitParam; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.compress.utils.IOUtils; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.http.HttpStatus; +import org.json.JSONException; +import org.json.JSONObject; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.components.HumanPolicyComponent; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.controller.PolicyExportAndImportController; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.XACMLRest; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.ActionBodyEntity; +import org.openecomp.policy.rest.jpa.ConfigurationDataEntity; +import org.openecomp.policy.rest.jpa.PolicyEditorScopes; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.UserInfo; +import org.openecomp.policy.utils.PolicyUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import org.openecomp.portalsdk.core.web.support.UserUtils; + +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +@WebServlet(value ="/fm/*", loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") }) +public class PolicyManagerServlet extends HttpServlet { + private static final Logger LOGGER = FlexLogger.getLogger(PolicyManagerServlet.class); + private static final long serialVersionUID = -8453502699403909016L; + + private enum Mode { + LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT + } + + private static String CONTENTTYPE = "application/json"; + private static String SUPERADMIN = "super-admin"; + private static String SUPEREDITOR = "super-editor"; + private static String SUPERGUEST = "super-guest"; + private static String ADMIN = "admin"; + private static String EDITOR = "editor"; + private static String GUEST = "guest"; + private static String RESULT = "result"; + + private static Path closedLoopJsonLocation; + private static JsonArray policyNames; + + public static JsonArray getPolicyNames() { + return policyNames; + } + + public static void setPolicyNames(JsonArray policyNames) { + PolicyManagerServlet.policyNames = policyNames; + } + + private static List serviceTypeNamesList = new ArrayList(); + + public static List getServiceTypeNamesList() { + return serviceTypeNamesList; + } + + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + // + // Common initialization + // + XACMLRest.xacmlInit(servletConfig); + // + //Initialize ClosedLoop JSON + // + PolicyManagerServlet.initializeJSONLoad(); + } + + protected static void initializeJSONLoad() { + closedLoopJsonLocation = Paths.get(XACMLProperties + .getProperty(XACMLRestProperties.PROP_ADMIN_CLOSEDLOOP)); + FileInputStream inputStream = null; + String location = closedLoopJsonLocation.toString(); + try { + inputStream = new FileInputStream(location); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } + if (location.endsWith("json")) { + JsonReader jsonReader = null; + jsonReader = Json.createReader(inputStream); + policyNames = jsonReader.readArray(); + serviceTypeNamesList = new ArrayList(); + for (int i = 0; i < policyNames.size(); i++) { + javax.json.JsonObject policyName = policyNames.getJsonObject(i); + String name = policyName.getJsonString("serviceTypePolicyName").getString(); + serviceTypeNamesList.add(name); + } + jsonReader.close(); + } + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + LOGGER.debug("doPost"); + try { + // if request contains multipart-form-data + if (ServletFileUpload.isMultipartContent(request)) { + uploadFile(request, response); + } + // all other post request has json params in body + else { + fileOperation(request, response); + } + } catch (Exception e) { + setError(e, response); + } + } + + //Set Error Message for Exception + private void setError(Exception t, HttpServletResponse response) throws IOException { + try { + JSONObject responseJsonObject = error(t.getMessage()); + response.setContentType(CONTENTTYPE); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } catch (Exception x) { + response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage()); + } + } + + //Policy Import Functionality + private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException { + try { + String newFile; + Map files = new HashMap(); + + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + for (FileItem item : items) { + if (!item.isFormField()) { + // Process form file field (input type="file"). + files.put(item.getName(), item.getInputStream()); + if(item.getName().endsWith(".xls")){ + try{ + File file = new File(item.getName()); + OutputStream outputStream = new FileOutputStream(file); + IOUtils.copy(item.getInputStream(), outputStream); + outputStream.close(); + newFile = file.toString(); + PolicyExportAndImportController importController = new PolicyExportAndImportController(); + importController.importRepositoryFile(newFile, request); + }catch(Exception e){ + LOGGER.error("Upload error : " + e); + } + } + } + } + + JSONObject responseJsonObject = null; + responseJsonObject = this.success(); + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } catch (Exception e) { + LOGGER.debug("Cannot write file"); + throw new ServletException("Cannot write file", e); + } + } + + //File Operation Functionality + private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject responseJsonObject = null; + try { + StringBuilder sb = new StringBuilder(); + BufferedReader br = request.getReader(); + String str; + while ((str = br.readLine()) != null) { + sb.append(str); + } + br.close(); + JSONObject jObj = new JSONObject(sb.toString()); + JSONObject params = jObj.getJSONObject("params"); + Mode mode = Mode.valueOf(params.getString("mode")); + switch (mode) { + case ADDFOLDER: + responseJsonObject = addFolder(params, request); + break; + case COPY: + responseJsonObject = copy(params, request); + break; + case DELETE: + responseJsonObject = delete(params, request); + break; + case EDITFILE: + responseJsonObject = editFile(params); + break; + case VIEWPOLICY: + responseJsonObject = editFile(params); + break; + case LIST: + responseJsonObject = list(params, request); + break; + case RENAME: + responseJsonObject = rename(params, request); + break; + case DESCRIBEPOLICYFILE: + responseJsonObject = describePolicy(params); + break; + case ADDSUBSCOPE: + responseJsonObject = addFolder(params, request); + break; + case SWITCHVERSION: + responseJsonObject = switchVersion(params, request); + break; + default: + throw new ServletException("not implemented"); + } + if (responseJsonObject == null) { + responseJsonObject = error("generic error : responseJsonObject is null"); + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e); + responseJsonObject = error(e.getMessage()); + } + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } + + //Switch Version Functionality + private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{ + String path = params.getString("path"); + String userId = null; + try { + userId = UserUtils.getUserSession(request).getOrgUserId(); + } catch (Exception e) { + LOGGER.error("Exception Occured while reading userid from cookie" +e); + } + String policyName; + String removeExtension = path.replace(".xml", ""); + if(path.startsWith("/")){ + policyName = removeExtension.substring(1, removeExtension.lastIndexOf(".")); + }else{ + policyName = removeExtension.substring(0, removeExtension.lastIndexOf(".")); + } + + String activePolicy = null; + PolicyController controller = new PolicyController(); + if(params.toString().contains("activeVersion")){ + String activeVersion = params.getString("activeVersion"); + String highestVersion = params.get("highestVersion").toString(); + if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){ + return error("The Version shouldn't be greater than Highest Value"); + }else{ + activePolicy = policyName + "." + activeVersion + ".xml"; + String dbCheckName = activePolicy.replace("/", "."); + if(dbCheckName.contains("Config_")){ + dbCheckName = dbCheckName.replace(".Config_", ":Config_"); + }else if(dbCheckName.contains("Action_")){ + dbCheckName = dbCheckName.replace(".Action_", ":Action_"); + }else if(dbCheckName.contains("Decision_")){ + dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); + } + String[] splitDBCheckName = dbCheckName.split(":"); + String peQuery = "FROM PolicyEntity where policyName = '"+splitDBCheckName[1]+"' and scope ='"+splitDBCheckName[0]+"'"; + List policyEntity = controller.getDataByQuery(peQuery); + PolicyEntity pentity = (PolicyEntity) policyEntity.get(0); + if(pentity.isDeleted()){ + return error("The Policy is Not Existing in Workspace"); + }else{ + if(policyName.contains("/")){ + policyName = policyName.replace("/", File.separator); + } + policyName = policyName.substring(policyName.indexOf(File.separator)+1); + if(policyName.contains("\\")){ + policyName = policyName.replace(File.separator, "\\"); + } + policyName = splitDBCheckName[0].replace(".", File.separator)+File.separator+policyName; + String watchPolicyName = policyName; + if(policyName.contains("/")){ + policyName = policyName.replace("/", File.separator); + } + if(policyName.contains("\\")){ + policyName = policyName.replace("\\", "\\\\"); + } + String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='"+policyName+"' and id >0"; + //query the database + controller.executeQuery(query); + //Policy Notification + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(watchPolicyName); + entity.setActiveVersion(Integer.parseInt(activeVersion)); + entity.setModifiedBy(userId); + controller.watchPolicyFunction(entity, activePolicy, "SwitchVersion"); + return success(); + } + } + } + return controller.switchVersionPolicyContent(policyName); + } + + //Describe Policy + private JSONObject describePolicy(JSONObject params) throws ServletException{ + JSONObject object = null; + String path = params.getString("path"); + String policyName = null; + if(path.startsWith("/")){ + path = path.substring(1); + policyName = path.substring(path.lastIndexOf("/") +1); + path = path.replace("/", "."); + }else{ + path = path.replace("/", "."); + } + if(path.contains("Config_")){ + path = path.replace(".Config_", ":Config_"); + }else if(path.contains("Action_")){ + path = path.replace(".Action_", ":Action_"); + }else if(path.contains("Decision_")){ + path = path.replace(".Decision_", ":Decision_"); + } + PolicyController controller = new PolicyController(); + String[] split = path.split(":"); + String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; + List queryData = controller.getDataByQuery(query); + if(queryData != null){ + PolicyEntity entity = (PolicyEntity) queryData.get(0); + File temp = null; + try { + temp = File.createTempFile(policyName, ".tmp"); + BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); + bw.write(entity.getPolicyData()); + bw.close(); + object = HumanPolicyComponent.DescribePolicy(temp); + } catch (IOException e) { + e.printStackTrace(); + }finally{ + temp.delete(); + } + }else{ + return error("Error Occured while Describing the Policy"); + } + + return object; + } + + //Get the List of Policies and Scopes for Showing in Editor tab + private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException { + Set scopes = null; + List roles = null; + try { + //Get the Login Id of the User from Request + String userId = UserUtils.getUserSession(request).getOrgUserId(); + //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(Object role: userRoles){ + Roles userRole = (Roles) role; + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { + if(scopes.isEmpty()){ + return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + } + } + + List resultList = new ArrayList(); + boolean onlyFolders = params.getBoolean("onlyFolders"); + String path = params.getString("path"); + if(path.contains("..xml")){ + path = path.replaceAll("..xml", "").trim(); + } + + + if("/".equals(path)){ + if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + List scopesList = queryPolicyEditorScopes(null); + for(Object list : scopesList){ + PolicyEditorScopes scope = (PolicyEditorScopes) list; + if(!(scope.getScopeName().contains(File.separator))){ + JSONObject el = new JSONObject(); + el.put("name", scope.getScopeName()); + el.put("date", scope.getCreatedDate()); + el.put("size", ""); + el.put("type", "dir"); + el.put("createdBy", scope.getUserCreatedBy().getUserName()); + el.put("modifiedBy", scope.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } + }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){ + for(Object scope : scopes){ + JSONObject el = new JSONObject(); + List scopesList = queryPolicyEditorScopes(scope.toString()); + PolicyEditorScopes scopeById = (PolicyEditorScopes) scopesList.get(0); + el.put("name", scopeById.getScopeName()); + el.put("date", scopeById.getCreatedDate()); + el.put("size", ""); + el.put("type", "dir"); + el.put("createdBy", scopeById.getUserCreatedBy().getUserName()); + el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } + }else{ + try{ + String scopeName = path.substring(path.indexOf("/") +1); + activePolicyList(scopeName, resultList, roles, scopes, onlyFolders); + } catch (Exception ex) { + LOGGER.error("Error Occured While reading Policy Files List"+ex ); + } + } + + return new JSONObject().put(RESULT, resultList); + } catch (Exception e) { + LOGGER.error("list", e); + return error(e.getMessage()); + } + } + + private List queryPolicyEditorScopes(String scopeName){ + String scopeNamequery = ""; + if(scopeName == null){ + scopeNamequery = "from PolicyEditorScopes"; + }else{ + scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"'"; + } + PolicyController controller = new PolicyController(); + List scopesList = controller.getDataByQuery(scopeNamequery); + return scopesList; + } + + //Get Active Policy List based on Scope Selection form Policy Version table + private void activePolicyList(String scopeName, List resultList, List roles, Set scopes, boolean onlyFolders){ + PolicyController controller = new PolicyController(); + if(scopeName.contains("/")){ + scopeName = scopeName.replace("/", File.separator); + } + if(scopeName.contains("\\")){ + scopeName = scopeName.replace("\\", "\\\\\\\\"); + } + String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'"; + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; + List activePolicies = controller.getDataByQuery(query); + List scopesList = controller.getDataByQuery(scopeNamequery); + for(Object list : scopesList){ + PolicyEditorScopes scopeById = (PolicyEditorScopes) list; + String scope = scopeById.getScopeName(); + if(scope.contains(File.separator)){ + String checkScope = scope.substring(0, scope.lastIndexOf(File.separator)); + if(scopeName.contains("\\\\")){ + scopeName = scopeName.replace("\\\\", File.separator); + } + if(scope.contains(File.separator)){ + scope = scope.substring(checkScope.length()+1); + if(scope.contains(File.separator)){ + scope = scope.substring(0, scope.indexOf(File.separator)); + } + } + if(scopeName.equalsIgnoreCase(checkScope)){ + JSONObject el = new JSONObject(); + el.put("name", scope); + el.put("date", scopeById.getModifiedDate()); + el.put("size", ""); + el.put("type", "dir"); + el.put("createdBy", scopeById.getUserCreatedBy().getUserName()); + el.put("modifiedBy", scopeById.getUserModifiedBy().getUserName()); + resultList.add(el); + } + } + } + String scopeNameCheck = null; + for (Object list : activePolicies) { + PolicyVersion policy = (PolicyVersion) list; + String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator)); + if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + if((scopeName.contains("\\\\"))){ + scopeNameCheck = scopeName.replace("\\\\", File.separator); + }else{ + scopeNameCheck = scopeName; + } + if(scopeNameValue.equals(scopeNameCheck)){ + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1)); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + }else if(!scopes.isEmpty()){ + if(scopes.contains(scopeNameValue)){ + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().substring(policy.getPolicyName().lastIndexOf(File.separator)+1)); + el.put("date", policy.getModifiedDate()); + el.put("version", policy.getActiveVersion()); + el.put("size", ""); + el.put("type", "file"); + el.put("createdBy", getUserName(policy.getCreatedBy())); + el.put("modifiedBy", getUserName(policy.getModifiedBy())); + resultList.add(el); + } + } + } + } + + private String getUserName(String loginId){ + PolicyController controller = new PolicyController(); + UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId); + return userInfo.getUserName(); + } + + //Rename Policy + private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException { + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + String oldPath = params.getString("path"); + String newPath = params.getString("newPath"); + oldPath = oldPath.substring(oldPath.indexOf("/")+1); + newPath = newPath.substring(newPath.indexOf("/")+1); + if(oldPath.endsWith(".xml")){ + policyRename(oldPath, newPath, userId); + }else{ + String scopeName = oldPath; + String newScopeName = newPath; + if(scopeName.contains("/")){ + scopeName = scopeName.replace("/", File.separator); + newScopeName = newScopeName.replace("/", File.separator); + } + if(scopeName.contains("\\")){ + scopeName = scopeName.replace("\\", "\\\\\\\\"); + newScopeName = newScopeName.replace("\\", "\\\\\\\\"); + } + PolicyController controller = new PolicyController(); + String query = "from PolicyVersion where POLICY_NAME like'" +scopeName+"%'"; + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +scopeName+"%'"; + List activePolicies = controller.getDataByQuery(query); + List scopesList = controller.getDataByQuery(scopeNamequery); + for(Object object : activePolicies){ + PolicyVersion activeVersion = (PolicyVersion) object; + String policyOldPath = activeVersion.getPolicyName().replace(File.separator, "/") + "." + activeVersion.getActiveVersion() + ".xml"; + String policyNewPath = policyOldPath.replace(oldPath, newPath); + policyRename(policyOldPath, policyNewPath, userId); + } + for(Object object : scopesList){ + PolicyEditorScopes editorScopeEntity = (PolicyEditorScopes) object; + if(scopeName.contains("\\\\\\\\")){ + scopeName = scopeName.replace("\\\\\\\\", File.separator); + newScopeName = newScopeName.replace("\\\\\\\\", File.separator); + } + String scope = editorScopeEntity.getScopeName().replace(scopeName, newScopeName); + editorScopeEntity.setScopeName(scope); + controller.updateData(editorScopeEntity); + } + } + return success(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); + return error(e.getMessage()); + } + } + + private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException { + try { + PolicyEntity entity = null; + PolicyController controller = new PolicyController(); + + String policyVersionName = newPath.replace(".xml", ""); + String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator); + + String oldpolicyVersionName = oldPath.replace(".xml", ""); + String oldpolicyName = oldpolicyVersionName.substring(0, oldpolicyVersionName.lastIndexOf(".")).replace("/", File.separator); + + String newpolicyName = newPath.replace("/", "."); + String newPolicyCheck = newpolicyName; + if(newPolicyCheck.contains("Config_")){ + newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_"); + }else if(newPolicyCheck.contains("Action_")){ + newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_"); + }else if(newPolicyCheck.contains("Decision_")){ + newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_"); + } + String[] newPolicySplit = newPolicyCheck.split(":"); + + String orignalPolicyName = oldPath.replace("/", "."); + String oldPolicyCheck = orignalPolicyName; + if(oldPolicyCheck.contains("Config_")){ + oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_"); + }else if(oldPolicyCheck.contains("Action_")){ + oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_"); + }else if(oldPolicyCheck.contains("Decision_")){ + oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_"); + } + String[] oldPolicySplit = oldPolicyCheck.split(":"); + + //Check PolicyEntity table with newPolicy Name + String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'"; + System.out.println(policyEntityquery); + List queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + entity = (PolicyEntity) queryData.get(0); + } + + if(entity != null){ + //if a policy exists with new name check if it is deleted or not + if(entity.isDeleted()){ + //Check Policy Group Entity table if policy has been pushed or not + String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'"; + List object = controller.getDataByQuery(query); + if(object.isEmpty()){ + //if PolicyGroupEntity data is empty delete the entry from database + controller.deleteData(entity); + //Query the Policy Entity with oldPolicy Name + String oldpolicyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; + System.out.println(oldpolicyEntityquery); + List oldEntityData = controller.getDataByQuery(oldpolicyEntityquery); + if(!oldEntityData.isEmpty()){ + entity = (PolicyEntity) oldEntityData.get(0); + } + checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0], newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId); + }else{ + return error("Policy rename failed due to policy with new name existing in PDP Group."); + } + }else{ + return error("Policy rename failed due to same name existing."); + } + }else{ + //Query the Policy Entity with oldPolicy Name + String oldpolicyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; + System.out.println(oldpolicyEntityquery); + List oldEntityData = controller.getDataByQuery(oldpolicyEntityquery); + if(!oldEntityData.isEmpty()){ + entity = (PolicyEntity) oldEntityData.get(0); + } + checkOldPolicyEntryAndUpdate(entity, newPolicySplit[0] , newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], policyName, newpolicyName, oldpolicyName, userId); + } + + return success(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); + return error(e.getMessage()); + } + } + + private JSONObject checkOldPolicyEntryAndUpdate(PolicyEntity entity, String newScope, String removenewPolicyExtension, String oldScope, String removeoldPolicyExtension, + String policyName, String newpolicyName, String oldpolicyName, String userId) throws ServletException{ + try { + ConfigurationDataEntity configEntity; + ActionBodyEntity actionEntity; + PolicyController controller = new PolicyController(); + configEntity = entity.getConfigurationData(); + actionEntity = entity.getActionBodyEntity(); + if(entity != null){ + //Check Policy Group Entity table if policy has been pushed or not + String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'"; + List object = controller.getDataByQuery(query); + if(object == null){ + String oldPolicyNameWithoutExtension = removeoldPolicyExtension; + String newPolicyNameWithoutExtension = removenewPolicyExtension; + if(removeoldPolicyExtension.endsWith(".xml")){ + oldPolicyNameWithoutExtension = oldPolicyNameWithoutExtension.substring(0, oldPolicyNameWithoutExtension.indexOf(".")); + newPolicyNameWithoutExtension = newPolicyNameWithoutExtension.substring(0, newPolicyNameWithoutExtension.indexOf(".")); + } + entity.setPolicyName(entity.getPolicyName().replace(removeoldPolicyExtension, removenewPolicyExtension)); + entity.setPolicyData(entity.getPolicyData().replace(oldScope +"."+oldPolicyNameWithoutExtension, newScope+"."+newPolicyNameWithoutExtension)); + entity.setScope(newScope); + entity.setModifiedBy(userId); + String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", ""); + String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", ""); + if(newpolicyName.contains("Config_")){ + configEntity.setConfigurationName(configEntity.getConfigurationName().replace(oldScope +"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension)); + controller.updateData(configEntity); + }else if(newpolicyName.contains("Action_")){ + actionEntity.setActionBody(actionEntity.getActionBody().replace(oldScope +"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension)); + controller.updateData(actionEntity); + } + controller.updateData(entity); + }else{ + //Mark as Deleted in PolicyEntiy table + entity.setDeleted(true); + controller.updateData(entity); + //Mark as Deleted in ConfigurationDataEntity table + configEntity.setDeleted(true); + controller.updateData(configEntity); + //Mark as Deleted in ActionDataEntity table + actionEntity.setDeleted(true); + controller.updateData(actionEntity); + //Clone New Copy + cloneRecord(newpolicyName, oldScope, removeoldPolicyExtension, newScope, removenewPolicyExtension, entity, userId); + } + + PolicyVersion versionEntity = (PolicyVersion) controller.getEntityItem(PolicyVersion.class, "policyName", oldpolicyName); + versionEntity.setPolicyName(policyName); + versionEntity.setModifiedBy(userId); + controller.updateData(versionEntity); + String movePolicyCheck = policyName.substring(policyName.lastIndexOf(File.separator)+1); + String moveOldPolicyCheck = oldpolicyName.substring(oldpolicyName.lastIndexOf(File.separator)+1); + if(movePolicyCheck.equals(moveOldPolicyCheck)){ + controller.watchPolicyFunction(versionEntity, oldpolicyName, "Move"); + }else{ + controller.watchPolicyFunction(versionEntity, oldpolicyName, "Rename"); + } + } + return success(); + } catch (Exception e) { + e.printStackTrace(); + return error(e.getMessage()); + } + } + + private JSONObject cloneRecord(String newpolicyName, String oldScope, String removeoldPolicyExtension, String newScope, String removenewPolicyExtension, PolicyEntity entity, String userId) throws ServletException{ + String queryEntityName = null; + PolicyController controller = new PolicyController(); + PolicyEntity cloneEntity = new PolicyEntity(); + cloneEntity.setPolicyName(newpolicyName); + removeoldPolicyExtension = removeoldPolicyExtension.replace(".xml", ""); + removenewPolicyExtension = removenewPolicyExtension.replace(".xml", ""); + cloneEntity.setPolicyData(entity.getPolicyData().replace(oldScope+"."+removeoldPolicyExtension, newScope+"."+removenewPolicyExtension)); + cloneEntity.setScope(entity.getScope()); + String oldConfigRemoveExtension = removeoldPolicyExtension.replace(".xml", ""); + String newConfigRemoveExtension = removenewPolicyExtension.replace(".xml", ""); + if(newpolicyName.contains("Config_")){ + ConfigurationDataEntity configurationDataEntity = new ConfigurationDataEntity(); + configurationDataEntity.setConfigurationName(entity.getConfigurationData().getConfigurationName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension)); + queryEntityName = configurationDataEntity.getConfigurationName(); + configurationDataEntity.setConfigBody(entity.getConfigurationData().getConfigBody()); + configurationDataEntity.setConfigType(entity.getConfigurationData().getConfigType()); + configurationDataEntity.setDeleted(false); + configurationDataEntity.setCreatedBy(userId); + configurationDataEntity.setModifiedBy(userId); + controller.saveData(configurationDataEntity); + ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) controller.getEntityItem(ConfigurationDataEntity.class, "configurationName", queryEntityName); + cloneEntity.setConfigurationData(configEntiy); + }else if(newpolicyName.contains("Action_")){ + ActionBodyEntity actionBodyEntity = new ActionBodyEntity(); + actionBodyEntity.setActionBodyName(entity.getActionBodyEntity().getActionBodyName().replace(oldScope+"."+oldConfigRemoveExtension, newScope+"."+newConfigRemoveExtension)); + queryEntityName = actionBodyEntity.getActionBodyName(); + actionBodyEntity.setActionBody(entity.getActionBodyEntity().getActionBody()); + actionBodyEntity.setDeleted(false); + actionBodyEntity.setCreatedBy(userId); + actionBodyEntity.setModifiedBy(userId); + controller.saveData(actionBodyEntity); + ActionBodyEntity actionEntiy = (ActionBodyEntity) controller.getEntityItem(ActionBodyEntity.class, "actionBodyName", queryEntityName); + cloneEntity.setActionBodyEntity(actionEntiy); + } + cloneEntity.setDeleted(entity.isDeleted()); + cloneEntity.setCreatedBy(userId); + cloneEntity.setModifiedBy(userId); + controller.saveData(cloneEntity); + + return success(); + } + + //Clone the Policy + private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException { + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + String oldPath = params.getString("path"); + String newPath = params.getString("newPath"); + oldPath = oldPath.substring(oldPath.indexOf("/")+1); + newPath = newPath.substring(newPath.indexOf("/")+1); + + String policyVersionName = newPath.replace(".xml", ""); + String version = policyVersionName.substring(policyVersionName.indexOf(".")+1); + String policyName = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")).replace("/", File.separator); + + String newpolicyName = newPath.replace("/", "."); + + String orignalPolicyName = oldPath.replace("/", "."); + + String newPolicyCheck = newpolicyName; + if(newPolicyCheck.contains("Config_")){ + newPolicyCheck = newPolicyCheck.replace(".Config_", ":Config_"); + }else if(newPolicyCheck.contains("Action_")){ + newPolicyCheck = newPolicyCheck.replace(".Action_", ":Action_"); + }else if(newPolicyCheck.contains("Decision_")){ + newPolicyCheck = newPolicyCheck.replace(".Decision_", ":Decision_"); + } + String[] newPolicySplit = newPolicyCheck.split(":"); + + String oldPolicyCheck = orignalPolicyName; + if(oldPolicyCheck.contains("Config_")){ + oldPolicyCheck = oldPolicyCheck.replace(".Config_", ":Config_"); + }else if(oldPolicyCheck.contains("Action_")){ + oldPolicyCheck = oldPolicyCheck.replace(".Action_", ":Action_"); + }else if(oldPolicyCheck.contains("Decision_")){ + oldPolicyCheck = oldPolicyCheck.replace(".Decision_", ":Decision_"); + } + String[] oldPolicySplit = oldPolicyCheck.split(":"); + + PolicyController controller = new PolicyController(); + + PolicyEntity entity = null; + boolean success = false; + + //Check PolicyEntity table with newPolicy Name + String policyEntityquery = "FROM PolicyEntity where policyName = '"+newPolicySplit[1]+"' and scope ='"+newPolicySplit[0]+"'"; + System.out.println(policyEntityquery); + List queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + entity = (PolicyEntity) queryData.get(0); + } + if(entity != null){ + //if a policy exists with new name check if it is deleted or not + if(entity.isDeleted()){ + //Check Policy Group Entity table if policy has been pushed or not + String query = "from PolicyGroupEntity where policyid = '"+entity.getPolicyId()+"'"; + List object = controller.getDataByQuery(query); + if(object == null){ + //if PolicyGroupEntity data is empty delete the entry from database + controller.deleteData(entity); + //Query the Policy Entity with oldPolicy Name + policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; + System.out.println(policyEntityquery); + queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + entity = (PolicyEntity) queryData.get(0); + } + if(entity != null){ + cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId); + success = true; + } + }else{ + return error("Policy Clone failed due to policy with new name existing in PDP Group."); + } + }else{ + return error("Policy Clone failed due to same name existing."); + } + }else{ + //Query the Policy Entity with oldPolicy Name + policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; + System.out.println(policyEntityquery); + queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + entity = (PolicyEntity) queryData.get(0); + } + if(entity != null){ + cloneRecord(newPolicySplit[1], oldPolicySplit[0], oldPolicySplit[1], newPolicySplit[0], newPolicySplit[1], entity, userId); + success = true; + } + } + if(success){ + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(Integer.parseInt(version)); + entityItem.setHigherVersion(Integer.parseInt(version)); + entityItem.setPolicyName(policyName); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + controller.saveData(entityItem); + } + + LOGGER.debug("copy from: {} to: {}" + oldPath +newPath); + + return success(); + } catch (Exception e) { + LOGGER.error("copy", e); + return error(e.getMessage()); + } + } + + //Delete Policy or Scope Functionality + private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException { + PolicyController controller = new PolicyController(); + PolicyRestController restController = new PolicyRestController(); + PolicyEntity policyEntity = null; + String policyNamewithoutExtension; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + String deleteVersion = ""; + String path = params.getString("path"); + LOGGER.debug("delete {}" +path); + if(params.has("deleteVersion")){ + deleteVersion = params.getString("deleteVersion"); + } + path = path.substring(path.indexOf("/")+1); + String policyNamewithExtension = path.replace("/", File.separator); + String policyVersionName = policyNamewithExtension.replace(".xml", ""); + String query = ""; + if(path.endsWith(".xml")){ + policyNamewithoutExtension = policyVersionName.substring(0, policyVersionName.lastIndexOf(".")); + policyNamewithoutExtension = policyNamewithoutExtension.replace(File.separator, "."); + String splitPolicyName = null; + if(policyNamewithoutExtension.contains("Config_")){ + splitPolicyName = policyNamewithoutExtension.replace(".Config_", ":Config_"); + }else if(policyNamewithoutExtension.contains("Action_")){ + splitPolicyName = policyNamewithoutExtension.replace(".Action_", ":Action_"); + }else if(policyNamewithoutExtension.contains("Decision_")){ + splitPolicyName = policyNamewithoutExtension.replace(".Decision_", ":Decision_"); + } + String[] split = splitPolicyName.split(":"); + query = "FROM PolicyEntity where policyName like '"+split[1]+"%' and scope ='"+split[0]+"'"; + }else{ + policyNamewithoutExtension = path.replace(File.separator, "."); + query = "FROM PolicyEntity where scope like '"+policyNamewithoutExtension+"%'"; + } + + List policyEntityobjects = controller.getDataByQuery(query); + boolean pdpCheck = true; + if(path.endsWith(".xml")){ + policyNamewithoutExtension = policyNamewithoutExtension.replace(".", File.separator); + int version = Integer.parseInt(policyVersionName.substring(policyVersionName.indexOf(".")+1)); + if("ALL".equals(deleteVersion)){ + if(!policyEntityobjects.isEmpty()){ + for(Object object : policyEntityobjects){ + policyEntity = (PolicyEntity) object; + String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; + List groupobject = controller.getDataByQuery(groupEntityquery); + if(groupobject != null){ + pdpCheck = false; + break; + } + } + } + if(pdpCheck){ + for(Object object : policyEntityobjects){ + policyEntity = (PolicyEntity) object; + //Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + //Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + if(policyNamewithoutExtension.contains("Config_")){ + controller.deleteData(policyEntity.getConfigurationData()); + }else if(policyNamewithoutExtension.contains("Action_")){ + controller.deleteData(policyEntity.getActionBodyEntity()); + } + } + //Policy Notification + PolicyVersion versionEntity = new PolicyVersion(); + versionEntity.setPolicyName(policyNamewithoutExtension); + versionEntity.setModifiedBy(userId); + controller.watchPolicyFunction(versionEntity, policyNamewithExtension, "DeleteAll"); + //Delete from policyVersion table + String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + controller.executeQuery(policyVersionQuery); + } + }else{ + return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'"); + } + }else if("CURRENT".equals(deleteVersion)){ + String currentVersionPolicyName = policyNamewithExtension.substring(policyNamewithExtension.lastIndexOf(File.separator)+1); + String currentVersionScope = policyNamewithExtension.substring(0, policyNamewithExtension.lastIndexOf(File.separator)).replace(File.separator, "."); + query = "FROM PolicyEntity where policyName = '"+currentVersionPolicyName+"' and scope ='"+currentVersionScope+"'"; + List policyEntitys = controller.getDataByQuery(query); + if(!policyEntitys.isEmpty()){ + policyEntity = (PolicyEntity) policyEntitys.get(0); + } + if(policyEntity != null){ + String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; + List groupobject = controller.getDataByQuery(groupEntityquery); + if(groupobject == null){ + //Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + //Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + if(policyNamewithoutExtension.contains("Config_")){ + controller.deleteData(policyEntity.getConfigurationData()); + }else if(policyNamewithoutExtension.contains("Action_")){ + controller.deleteData(policyEntity.getActionBodyEntity()); + } + + if(version > 1){ + int highestVersion = 0; + if(policyEntityobjects.isEmpty()){ + for(Object object : policyEntityobjects){ + policyEntity = (PolicyEntity) object; + String policyEntityName = policyEntity.getPolicyName().replace(".xml", ""); + int policyEntityVersion = Integer.parseInt(policyEntityName.substring(policyEntityName.lastIndexOf(".")+1)); + if(policyEntityVersion > highestVersion){ + highestVersion = policyEntityVersion; + } + } + } + + //Policy Notification + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(policyNamewithoutExtension); + entity.setActiveVersion(highestVersion); + entity.setModifiedBy(userId); + controller.watchPolicyFunction(entity, policyNamewithExtension, "DeleteOne"); + + String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"'"; + controller.executeQuery(updatequery); + }else{ + String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + controller.executeQuery(policyVersionQuery); + } + } + }else{ + return error("Policy can't be deleted, it is active in PDP Groups. PolicyName: '"+policyEntity.getScope() + "." +policyEntity.getPolicyName()+"'"); + } + } + } + }else{ + if(!policyEntityobjects.isEmpty()){ + for(Object object : policyEntityobjects){ + policyEntity = (PolicyEntity) object; + String groupEntityquery = "from PolicyGroupEntity where policyid = '"+policyEntity.getPolicyId()+"'"; + List groupobject = controller.getDataByQuery(groupEntityquery); + if(groupobject != null){ + pdpCheck = false; + } + } + if(pdpCheck){ + for(Object object : policyEntityobjects){ + policyEntity = (PolicyEntity) object; + //Delete the entity from Elastic Search Database + String searchFileName = policyEntity.getScope() + "." + policyEntity.getPolicyName(); + restController.deleteElasticData(searchFileName); + //Delete the entity from Policy Entity table + controller.deleteData(policyEntity); + policyNamewithoutExtension = policyEntity.getPolicyName(); + if(policyNamewithoutExtension.contains("Config_")){ + controller.deleteData(policyEntity.getConfigurationData()); + }else if(policyNamewithoutExtension.contains("Action_")){ + controller.deleteData(policyEntity.getActionBodyEntity()); + } + } + + //Delete from policyVersion and policyEditor Scope table + String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + controller.executeQuery(policyVersionQuery); + controller.executeQuery(policyScopeQuery); + //Policy Notification + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(path); + entity.setModifiedBy(userId); + controller.watchPolicyFunction(entity, path, "DeleteScope"); + } + } + } + return success(); + } catch (Exception e) { + LOGGER.error("delete", e); + return error(e.getMessage()); + } + } + + //Edit the Policy + private JSONObject editFile(JSONObject params) throws ServletException { + // get content + try { + PolicyController controller = new PolicyController(); + String mode = params.getString("mode"); + String path = params.getString("path"); + LOGGER.debug("editFile path: {}"+ path); + + String domain = path.substring(1, path.lastIndexOf("/")); + domain = domain.replace("/", "."); + + path = path.substring(1); + path = path.replace("/", "."); + String dbCheckName = path; + if(dbCheckName.contains("Config_")){ + dbCheckName = dbCheckName.replace(".Config_", ":Config_"); + }else if(dbCheckName.contains("Action_")){ + dbCheckName = dbCheckName.replace(".Action_", ":Action_"); + }else if(dbCheckName.contains("Decision_")){ + dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); + } + + String[] split = dbCheckName.split(":"); + String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; + List queryData = controller.getDataByQuery(query); + PolicyEntity entity = (PolicyEntity) queryData.get(0); + InputStream stream = new ByteArrayInputStream(entity.getPolicyData().getBytes(StandardCharsets.UTF_8)); + + + Object policy = XACMLPolicyScanner.readPolicy(stream); + PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); + policyAdapter.setData(policy); + + if("viewPolicy".equalsIgnoreCase(mode)){ + policyAdapter.setReadOnly(true); + policyAdapter.setEditPolicy(false); + }else{ + policyAdapter.setReadOnly(false); + policyAdapter.setEditPolicy(true); + } + policyAdapter.setDomain(domain); + policyAdapter.setDomainDir(domain); + policyAdapter.setPolicyData(policy); + String policyName = path.replace(".xml", ""); + policyName = policyName.substring(0, policyName.lastIndexOf(".")); + policyAdapter.setPolicyName(policyName.substring(policyName.lastIndexOf(".")+1)); + + PolicyAdapter setpolicyAdapter = PolicyAdapter.getInstance(); + setpolicyAdapter.configure(policyAdapter,entity); + + policyAdapter.setParentPath(null); + ObjectMapper mapper = new ObjectMapper(); + String json = mapper.writeValueAsString(policyAdapter); + JsonNode jsonNode = mapper.readTree(json); + + return new JSONObject().put(RESULT, jsonNode); + } catch (Exception e) { + LOGGER.error("editFile", e); + return error(e.getMessage()); + } + } + + //Add Scopes + private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException { + PolicyController controller = new PolicyController(); + String name = ""; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + String path = params.getString("path"); + try{ + if(params.has("subScopename")){ + if(!params.getString("subScopename").equals("")){ + name = params.getString("path").replace("/", File.separator) + File.separator +params.getString("subScopename"); + } + }else{ + name = params.getString("name"); + } + }catch(Exception e){ + name = params.getString("name"); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e); + } + String validateName; + if(name.contains(File.separator)){ + validateName = name.substring(name.lastIndexOf(File.separator)+1); + }else{ + validateName = name; + } + if(!name.isEmpty()){ + String validate = PolicyUtils.emptyPolicyValidator(validateName); + if(!validate.contains("success")){ + return error(validate); + } + } + LOGGER.debug("addFolder path: {} name: {}" + path +name); + if(!name.equals("")){ + PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name); + if(entity == null){ + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + PolicyEditorScopes newScope = new PolicyEditorScopes(); + String scopeName = null; + if(name.startsWith(File.separator)){ + scopeName = name.substring(1); + }else{ + scopeName = name; + } + newScope.setScopeName(scopeName); + newScope.setUserCreatedBy(userInfo); + newScope.setUserModifiedBy(userInfo); + controller.saveData(newScope); + }else{ + return error("Scope Already Exists"); + } + } + return success(); + } catch (Exception e) { + LOGGER.error("addFolder", e); + return error(e.getMessage()); + } + } + + //Return Error Object + private JSONObject error(String msg) throws ServletException { + try { + JSONObject result = new JSONObject(); + result.put("success", false); + result.put("error", msg); + return new JSONObject().put(RESULT, result); + } catch (JSONException e) { + throw new ServletException(e); + } + } + + //Return Success Object + private JSONObject success() throws ServletException { + try { + JSONObject result = new JSONObject(); + result.put("success", true); + result.put("error", (Object) null); + return new JSONObject().put(RESULT, result); + } catch (JSONException e) { + throw new ServletException(e); + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java new file mode 100644 index 000000000..3aee634fd --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java @@ -0,0 +1,166 @@ +/*- + * ============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.admin; + +import java.io.File; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Properties; + +import javax.mail.MessagingException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.beans.factory.annotation.Configurable; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.mail.javamail.JavaMailSenderImpl; +import org.springframework.mail.javamail.MimeMessageHelper; + +@Configurable +public class PolicyNotificationMail{ + private static Logger LOGGER = FlexLogger.getLogger(PolicyNotificationMail.class); + + @Bean + public JavaMailSenderImpl javaMailSenderImpl(){ + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost(PolicyController.smtpHost); + mailSender.setPort(Integer.parseInt(PolicyController.smtpPort)); + mailSender.setUsername(PolicyController.smtpUsername); + mailSender.setPassword(PolicyController.smtpPassword); + Properties prop = mailSender.getJavaMailProperties(); + prop.put("mail.transport.protocol", "smtp"); + prop.put("mail.smtp.auth", "true"); + prop.put("mail.smtp.starttls.enable", "true"); + prop.put("mail.debug", "true"); + return mailSender; + } + + @SuppressWarnings("resource") + public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) throws MessagingException { + String from = PolicyController.smtpUsername; + String to = ""; + String subject = ""; + String message = ""; + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + if(mode.equalsIgnoreCase("EditPolicy")){ + subject = "Policy has been Updated : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Updated" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Modified By : " +entityItem.getModifiedBy() + '\n' + "Modified Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("Rename")){ + subject = "Policy has been Renamed : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Renamed" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Renamed By : " +entityItem.getModifiedBy() + '\n' + "Renamed Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("DeleteAll")){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted with All Versions" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("DeleteOne")){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' +"Policy Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("DeleteScope")){ + subject = "Scope has been Deleted : "+entityItem.getPolicyName(); + message = "The Scope Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Scope Name : " + policyName + '\n' + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("SwitchVersion")){ + subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been SwitchedVersion" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Switched By : " +entityItem.getModifiedBy() + '\n' + "Switched Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("Move")){ + subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Moved to Other Scope" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Moved By : " +entityItem.getModifiedBy() + '\n' + "Moved Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + String policyFileName = entityItem.getPolicyName(); + String checkPolicyName = policyFileName; + if(policyFileName.contains("/")){ + policyFileName = policyFileName.substring(0, policyFileName.indexOf("/")); + policyFileName = policyFileName.replace("/", File.separator); + } + if(policyFileName.contains("\\")){ + policyFileName = policyFileName.substring(0, policyFileName.indexOf("\\")); + policyFileName = policyFileName.replace("\\", "\\\\"); + } + + String query = "from WatchPolicyNotificationTable where policyName like'" +policyFileName+"%'"; + boolean sendFlag = false; + List watchList = policyNotificationDao.getDataByQuery(query); + if(watchList != null){ + if(watchList.size() > 0){ + for(Object watch : watchList){ + WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch; + String watchPolicyName = list.getPolicyName(); + if(watchPolicyName.contains("Config_")){ + if(watchPolicyName.equals(checkPolicyName)){ + sendFlag = true; + } + }else if(watchPolicyName.contains("Action_")){ + if(watchPolicyName.equals(checkPolicyName)){ + sendFlag = true; + } + }else if(watchPolicyName.contains("Decision_")){ + if(watchPolicyName.equals(checkPolicyName)){ + sendFlag = true; + } + }else{ + sendFlag = true; + } + if(sendFlag){ + to = list.getLoginIds()+"@"+PolicyController.smtpEmailExtension; + to = to.trim(); + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + ctx.register(PolicyNotificationMail.class); + ctx.refresh(); + JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class); + MimeMessage mimeMessage = mailSender.createMimeMessage(); + MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage); + try { + mailMsg.setFrom(new InternetAddress(from, "Policy Notification System")); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e); + } + mailMsg.setTo(to); + mailMsg.setSubject(subject); + mailMsg.setText(message); + mailSender.send(mimeMessage); + } + } + } + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java new file mode 100644 index 000000000..2a1129cf6 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyRestController.java @@ -0,0 +1,379 @@ +/*- + * ============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.admin; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.List; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.io.IOUtils; +import org.json.JSONObject; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.controller.CreateClosedLoopFaultController; +import org.openecomp.policy.controller.CreateDcaeMicroServiceController; +import org.openecomp.policy.controller.CreateFirewallController; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.utils.PolicyUtils; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +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.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.servlet.ModelAndView; + +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +@RestController +@RequestMapping("/") +public class PolicyRestController extends RestrictedBaseController{ + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyRestController.class); + + private String boundary = null; + + @Autowired + CommonClassDao commonClassDao; + + @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST}) + public ModelAndView policyCreationController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + + String userId = UserUtils.getUserSession(request).getOrgUserId(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + + PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.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.getConfigPolicyType() != null){ + if(policyData.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")){ + CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController(); + policyData = faultController.setDataToPolicyRestAdapter(policyData, root); + }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Firewall Config")){ + CreateFirewallController fwController = new CreateFirewallController(); + policyData = fwController.setDataToPolicyRestAdapter(policyData); + }else if(policyData.getConfigPolicyType().equalsIgnoreCase("Micro Service")){ + CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); + policyData = msController.setDataToPolicyRestAdapter(policyData, root); + } + } + + policyData.setUserId(userId); + + 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("\"", "")); + } + String result; + String body = PolicyUtils.objectToJsonString(policyData); + String uri = request.getRequestURI(); + ResponseEntity responseEntity = sendToPAP(body, uri, request, HttpMethod.POST); + if(responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){ + result = "PolicyExists"; + }else{ + result = responseEntity.getBody().toString(); + String policyName = responseEntity.getHeaders().get("policyName").get(0).toString(); + if(policyData.isEditPolicy){ + if(result.equalsIgnoreCase("success")){ + PolicyNotificationMail email = new PolicyNotificationMail(); + String mode = "EditPolicy"; + String watchPolicyName = policyName.replace(".xml", ""); + String version = watchPolicyName.substring(watchPolicyName.lastIndexOf(".")+1); + watchPolicyName = watchPolicyName.substring(0, watchPolicyName.lastIndexOf(".")).replace(".", File.separator); + String policyVersionName = watchPolicyName.replace(".", File.separator); + watchPolicyName = watchPolicyName + "." + version + ".xml"; + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setPolicyName(policyVersionName); + entityItem.setActiveVersion(Integer.parseInt(version)); + entityItem.setModifiedBy(userId); + email.sendMail(entityItem, watchPolicyName, mode, commonClassDao); + } + } + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(result); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + return null; + + } + + + private ResponseEntity sendToPAP(String body, String requestURI, HttpServletRequest request, HttpMethod method) throws Exception{ + String papUrl = PolicyController.papUrl; + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + LOGGER.info("User Id is " + papID + "Pass is: " + papPass); + + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + HttpHeaders headers = new HttpHeaders(); + headers.set("Authorization", "Basic " + encoding); + headers.set("Content-Type", "application/json"); + + RestTemplate restTemplate = new RestTemplate(); + HttpEntity requestEntity = new HttpEntity<>(body, headers); + ResponseEntity result = null; + HttpClientErrorException exception = null; + + try{ + result = ((ResponseEntity) restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class)); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); + exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); + if(e.getMessage().equals("409 Conflict")){ + return (ResponseEntity) ResponseEntity.ok(HttpServletResponse.SC_CONFLICT); + } + } + if(exception != null && exception.getStatusCode()!=null){ + if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){ + String message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ; + LOGGER.error(message); + throw new Exception(message, exception); + } + if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + LOGGER.error(message); + throw new Exception(message, exception); + } + if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){ + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception; + LOGGER.error(message); + throw new Exception(message, exception); + } + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + LOGGER.error(message); + throw new Exception(message, exception); + } + return result; + } + + private String callPAP(HttpServletRequest request, HttpServletResponse response, String method, String uri){ + String papUrl = PolicyController.papUrl; + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + LOGGER.info("User Id is " + papID + "Pass is: " + papPass); + + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + HttpHeaders headers = new HttpHeaders(); + headers.set("Authorization", "Basic " + encoding); + headers.set("Content-Type", "application/json"); + + + HttpURLConnection connection = null; + List items; + FileItem item = null; + File file = null; + if(uri.contains("import_dictionary")){ + try { + items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + item = items.get(0); + file = new File(item.getName()); + String newFile = file.toString(); + uri = uri +"&dictionaryName="+newFile; + } catch (Exception e2) { + e2.printStackTrace(); + } + } + + try { + URL url = new URL(papUrl + uri); + connection = (HttpURLConnection)url.openConnection(); + connection.setRequestMethod(method); + connection.setUseCaches(false); + connection.setInstanceFollowRedirects(false); + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setDoOutput(true); + connection.setDoInput(true); + + if(!uri.contains("searchPolicy")){ + if(!(uri.endsWith("set_BRMSParamData") || uri.contains("import_dictionary"))){ + connection.setRequestProperty("Content-Type","application/json"); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = null; + try { + root = mapper.readTree(request.getReader()); + }catch (Exception e1) { + e1.printStackTrace(); + } + + ObjectMapper mapper1 = new ObjectMapper(); + mapper1.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); + + Object obj = mapper1.treeToValue(root, Object.class); + String json = mapper1.writeValueAsString(obj); + + Object content = new ByteArrayInputStream(json.getBytes()); + + if (content != null && (content instanceof InputStream)) { + // send current configuration + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy((InputStream) content, os); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("copied to output, bytes=" + count); + } + } + } + }else{ + if(uri.endsWith("set_BRMSParamData")){ + connection.setRequestProperty("Content-Type","application/json"); + try (OutputStream os = connection.getOutputStream()) { + IOUtils.copy((InputStream) request.getInputStream(), os); + } + }else{ + boundary = "===" + System.currentTimeMillis() + "==="; + connection.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary); + try (OutputStream os = connection.getOutputStream()) { + IOUtils.copy((InputStream) item.getInputStream(), os); + } + } + } + } + + connection.connect(); + + int responseCode = connection.getResponseCode(); + if(responseCode == 200){ + // get the response content into a String + String responseJson = null; + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); + scanner.useDelimiter("\\A"); + responseJson = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + LOGGER.info("JSON response from PAP: " + responseJson); + return responseJson; + } + + } catch (Exception e) { + e.printStackTrace(); + }finally{ + if(file != null){ + if(file.exists()){ + file.delete(); + } + } + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = null; + try { + is = connection.getInputStream(); + } catch (Exception e1) { + // ignore this + } + if (is != null) { + is.close(); + } + + } catch (IOException ex) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + return null; + } + + @RequestMapping(value={"/getDictionary/*"}, method={RequestMethod.GET}) + public void getDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String uri = request.getRequestURI().replace("/getDictionary", ""); + String body = sendToPAP(null, uri, request, HttpMethod.GET).getBody().toString(); + response.getWriter().write(body); + } + + @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST}) + public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String uri = request.getRequestURI().replace("/saveDictionary", ""); + if(uri.contains("import_dictionary")){ + String userId = UserUtils.getUserSession(request).getOrgUserId(); + uri = uri+ "?userId=" +userId; + } + String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim()); + response.getWriter().write(body); + return null; + } + + @RequestMapping(value={"/deleteDictionary/*/*"}, method={RequestMethod.POST}) + public ModelAndView deletetDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String uri = request.getRequestURI().replace("/deleteDictionary", ""); + String body = callPAP(request, response, "POST", uri.replaceFirst("/", "").trim()); + response.getWriter().write(body); + return null; + } + + public void deleteElasticData(String fileName){ + String uri = "searchPolicy?action=delete&policyName='"+fileName+"'"; + callPAP(null, null, "POST", uri.trim()); + } + +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyUserInfoController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyUserInfoController.java new file mode 100644 index 000000000..97d26a4ee --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/PolicyUserInfoController.java @@ -0,0 +1,58 @@ +/*- + * ============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.admin; + +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.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +import org.openecomp.portalsdk.core.web.support.UserUtils; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; + +import com.fasterxml.jackson.databind.ObjectMapper; + +@Controller +@RequestMapping("/") +public class PolicyUserInfoController extends RestrictedBaseController{ + + @RequestMapping(value="/get_PolicyUserInfo", method = RequestMethod.GET) + private void getPolicyUserInfo(HttpServletRequest request, HttpServletResponse response){ + JsonMessage msg = null; + try { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + model.put("userid", userId); + msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } catch (Exception e) { + e.printStackTrace(); + } + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java new file mode 100644 index 000000000..d9fe9fa11 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java @@ -0,0 +1,528 @@ +/*- + * ============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.admin; + + + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.io.IOUtils; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDP; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; +import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDP; +import org.openecomp.policy.xacml.std.pap.StdPDPGroup; +import org.openecomp.policy.xacml.std.pap.StdPDPItemSetChangeNotifier; +import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDPStatus; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.type.CollectionType; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +/** + * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet + * through a RESTful interface + * + * + */ +public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine { + private static final Logger LOGGER = FlexLogger.getLogger(RESTfulPAPEngine.class); + + // + // URL of the PAP Servlet that this Admin Console talks to + // + private String papServletURLString; + + /** + * Set up link with PAP Servlet and get our initial set of Groups + * @throws Exception + */ + public RESTfulPAPEngine (String myURLString) throws PAPException, IOException { + // + // Get our URL to the PAP servlet + // + this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + if (this.papServletURLString == null || this.papServletURLString.length() == 0) { + String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP."; + LOGGER.error(message); + throw new PAPException(message); + } + + // + // register this Admin Console with the PAP Servlet to get updates + // + Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); + if (newURL != null) { + // assume this was a re-direct and try again + LOGGER.warn("Redirecting to '" + newURL + "'"); + this.papServletURLString = (String)newURL; + newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); + if (newURL != null) { + LOGGER.error("Failed to redirect to " + this.papServletURLString); + throw new PAPException("Failed to register with PAP"); + } + } + } + + + // + // High-level commands used by the Admin Console code through the PAPEngine Interface + // + + @Override + public EcompPDPGroup getDefaultGroup() throws PAPException { + EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "default="); + return newGroup; + } + + @Override + public void SetDefaultGroup(EcompPDPGroup group) throws PAPException { + sendToPAP("POST", null, null, null, "groupId=" + group.getId(), "default=true"); + } + + @SuppressWarnings("unchecked") + @Override + public Set getEcompPDPGroups() throws PAPException { + Set newGroupSet; + newGroupSet = (Set) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, "groupId="); + return Collections.unmodifiableSet(newGroupSet); + } + + + @Override + public EcompPDPGroup getGroup(String id) throws PAPException { + EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=" + id); + return newGroup; + } + + @Override + public void newGroup(String name, String description) + throws PAPException, NullPointerException { + String escapedName = null; + String escapedDescription = null; + try { + escapedName = URLEncoder.encode(name, "UTF-8"); + escapedDescription = URLEncoder.encode(description, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new PAPException("Unable to send name or description to PAP: " + e.getMessage()); + } + + this.sendToPAP("POST", null, null, null, "groupId=", "groupName="+escapedName, "groupDescription=" + escapedDescription); + } + + + /** + * Update the configuration on the PAP for a single Group. + * + * @param group + * @return + * @throws PAPException + */ + public void updateGroup(EcompPDPGroup group) throws PAPException { + + try { + + // + // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP! + // + // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace. + // + + + // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory. + // This is not efficient since most of the policies will already exist there. + // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any corrupted files on the PAP get refreshed. + + + // now update the group object on the PAP + + sendToPAP("PUT", group, null, null, "groupId=" + group.getId()); + } catch (Exception e) { + String message = "Unable to PUT policy '" + group.getId() + "', e:" + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + @Override + public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup) + throws PAPException, NullPointerException { + String moveToGroupString = null; + if (newGroup != null) { + moveToGroupString = "movePDPsToGroupId=" + newGroup.getId(); + } + sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), moveToGroupString); + } + + @Override + public EcompPDPGroup getPDPGroup(EcompPDP pdp) throws PAPException { + return getPDPGroup(pdp.getId()); + } + + + public EcompPDPGroup getPDPGroup(String pdpId) throws PAPException { + EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "pdpId=" + pdpId, "getPDPGroup="); + return newGroup; + } + + @Override + public EcompPDP getPDP(String pdpId) throws PAPException { + EcompPDP newPDP = (EcompPDP)sendToPAP("GET", null, null, StdPDP.class, "groupId=", "pdpId=" + pdpId); + return newPDP; + } + + @Override + public void newPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws PAPException, + NullPointerException { + StdPDP newPDP = new StdPDP(id, name, description, jmxport); + sendToPAP("PUT", newPDP, null, null, "groupId=" + group.getId(), "pdpId=" + id); + return; + } + + @Override + public void movePDP(EcompPDP pdp, EcompPDPGroup newGroup) throws PAPException { + sendToPAP("POST", null, null, null, "groupId=" + newGroup.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void updatePDP(EcompPDP pdp) throws PAPException { + EcompPDPGroup group = getPDPGroup(pdp); + sendToPAP("PUT", pdp, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void removePDP(EcompPDP pdp) throws PAPException { + EcompPDPGroup group = getPDPGroup(pdp); + sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId()); + return; + } + + //Validate the Policy Data + public boolean validatePolicyRequest(PolicyRestAdapter policyAdapter, String policyType) throws PAPException { + Boolean isValidData = false; + StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getConfigBodyData(), policyAdapter.getConfigType(), "Base"); + + //send JSON object to PAP + isValidData = (Boolean) sendToPAP("PUT", newPAPPolicy, null, null, "operation=validate", "apiflag=admin", "policyType=" + policyType); + return isValidData; + } + + + + @Override + public void publishPolicy(String id, String name, boolean isRoot, + InputStream policy, EcompPDPGroup group) throws PAPException { + + + // copy the (one) file into the target directory on the PAP servlet + copyFile(id, group, policy); + + // adjust the local copy of the group to include the new policy + PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name); + group.getPolicies().add(pdpPolicy); + + // tell the PAP servlet to include the policy in the configuration + updateGroup(group); + + return; + } + + /** + * Copy a single Policy file from the input stream to the PAP Servlet. + * Either this works (silently) or it throws an exception. + * + * @param policyId + * @param group + * @param policy + * @return + * @throws PAPException + */ + public void copyFile(String policyId, EcompPDPGroup group, InputStream policy) throws PAPException { + // send the policy file to the PAP Servlet + try { + sendToPAP("POST", policy, null, null, "groupId=" + group.getId(), "policyId="+policyId); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policyId + "', e:" + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + @Override + public void copyPolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException { + if (policy == null || group == null) { + throw new PAPException("Null input policy="+policy+" group="+group); + } + try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) { + copyFile(policy.getId(), group, is ); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + @Override + public void removePolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException { + throw new PAPException("NOT IMPLEMENTED"); + + } + + + /** + * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly + * to get detailed status info. + * + * @param pdp + * @return + * @throws PAPException + */ + + public PDPStatus getStatus(EcompPDP pdp) throws PAPException { + StdPDPStatus status = (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class); + return status; + } + + + // + // Internal Operations called by the PAPEngine Interface methods + // + + /** + * Send a request to the PAP Servlet and get the response. + * + * The content is either an InputStream to be copied to the Request OutputStream + * OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream. + * + * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller. + * + * @param method + * @param content - EITHER an InputStream OR an Object to be encoded in JSON + * @param collectionTypeClass + * @param responseContentClass + * @param parameters + * @return + * @throws Exception + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException { + HttpURLConnection connection = null; + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + LOGGER.info("User Id is " + papID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + LOGGER.info("Pass is: " + papPass); + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + LOGGER.info("Encoding for the PAP is: " + encoding); + try { + String fullURL = papServletURLString; + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + } + fullURL += "?" + queryString.substring(1); + } + + // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP + if (method.equals("GET") && (content instanceof EcompPDP) && responseContentClass == StdPDPStatus.class) { + // Adjust the url and properties appropriately + String pdpID =((EcompPDP)content).getId(); + fullURL = pdpID + "?type=Status"; + content = null; + if(CheckPDP.validateID(pdpID)){ + encoding = CheckPDP.getEncoding(pdpID); + } + } + + + URL url = new URL(fullURL); + + // + // Open up the connection + // + connection = (HttpURLConnection)url.openConnection(); + // + // Setup our method and headers + // + connection.setRequestMethod(method); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setDoOutput(true); + connection.setDoInput(true); + + if (content != null) { + if (content instanceof InputStream) { + try { + // + // Send our current policy configuration + // + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy((InputStream)content, os); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("copied to output, bytes="+count); + } + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e); + throw e; + } + } else { + // The content is an object to be encoded in JSON + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(connection.getOutputStream(), content); + } + } + // + // Do the connect + // + connection.connect(); + if (connection.getResponseCode() == 204) { + LOGGER.info("Success - no content."); + return null; + } else if (connection.getResponseCode() == 200) { + LOGGER.info("Success. We have a return object."); + String isValidData = connection.getHeaderField("isValidData"); + String isSuccess = connection.getHeaderField("successMapKey"); + Map successMap = new HashMap(); + if (isValidData != null && isValidData.equalsIgnoreCase("true")){ + LOGGER.info("Policy Data is valid."); + return true; + } else if (isValidData != null && isValidData.equalsIgnoreCase("false")) { + LOGGER.info("Policy Data is invalid."); + return false; + } else if (isSuccess != null && isSuccess.equalsIgnoreCase("success")) { + LOGGER.info("Policy Created Successfully!" ); + String finalPolicyPath = connection.getHeaderField("finalPolicyPath"); + successMap.put("success", finalPolicyPath); + return successMap; + } else if (isSuccess != null && isSuccess.equalsIgnoreCase("error")) { + LOGGER.info("There was an error while creating the policy!"); + successMap.put("error", "error"); + return successMap; + } else { + // get the response content into a String + String json = null; + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + LOGGER.info("JSON response from PAP: " + json); + + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + if (collectionTypeClass != null) { + // collection of objects expected + final CollectionType javaType = + mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass); + + Object objectFromJSON = mapper.readValue(json, javaType); + return objectFromJSON; + } else { + // single value object expected + Object objectFromJSON = mapper.readValue(json, responseContentClass); + return objectFromJSON; + } + } + + } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { + // redirection + String newURL = connection.getHeaderField("Location"); + if (newURL == null) { + LOGGER.error("No Location header to redirect to when response code="+connection.getResponseCode()); + throw new IOException("No redirect Location header when response code="+connection.getResponseCode()); + } + int qIndex = newURL.indexOf("?"); + if (qIndex > 0) { + newURL = newURL.substring(0, qIndex); + } + LOGGER.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); + return newURL; + } else { + LOGGER.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); + } + + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e); + throw new PAPException("Request/Response threw :" + e); + } finally { + // cleanup the connection + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = null; + try { + is = connection.getInputStream(); + } catch (Exception e1) { + // ignore this + } + if (is != null) { + is.close(); + } + + } catch (IOException ex) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java new file mode 100644 index 000000000..c80ccd6a6 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/HumanPolicyComponent.java @@ -0,0 +1,982 @@ +/*- + * ============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.components; + + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.FileSystems; +import java.nio.file.Path; +import java.util.Collection; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +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.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.AttributeSelectorType; +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.PolicySetType; +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.VariableReferenceType; + +import org.apache.commons.io.FilenameUtils; +import org.json.JSONObject; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.rest.jpa.FunctionDefinition; +import org.openecomp.policy.utils.XACMLPolicyWriterWithPapNotify; + +import com.att.research.xacml.api.AttributeValue; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAttribute; +import com.att.research.xacml.std.StdAttributeValue; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; +import com.att.research.xacml.util.XACMLPolicyScanner.SimpleCallback; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + + +public class HumanPolicyComponent{ + + private static final Logger LOGGER = FlexLogger.getLogger(HumanPolicyComponent.class); + + // Constants Used in XML Creation + public static final String CATEGORY_RECIPIENT_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:recipient-subject"; + public static final String CATEGORY_RESOURCE = "urn:oasis:names:tc:xacml:3.0:attribute-category:resource"; + public static final String CATEGORY_ACTION = "urn:oasis:names:tc:xacml:3.0:attribute-category:action"; + public static final String CATEGORY_ACCESS_SUBJECT = "urn:oasis:names:tc:xacml:1.0:subject-category:access-subject"; + public static final String ACTION_ID = "urn:oasis:names:tc:xacml:1.0:action:action-id"; + public static final String SUBJECT_ID = "urn:oasis:names:tc:xacml:1.0:subject:subject-id"; + public static final String RESOURCE_ID = "urn:oasis:names:tc:xacml:1.0:resource:resource-id"; + public static final String FUNTION_INTEGER_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:integer-one-and-only"; + public static final String FUNCTION_STRING_ONE_AND_ONLY = "urn:oasis:names:tc:xacml:1.0:function:string-one-and-only"; + public static final String FUNCTION_STRING_EQUAL = "urn:oasis:names:tc:xacml:1.0:function:string-equal"; + public static final String FUNCTION_STRING_REGEX_MATCH = "org.openecomp.function.regex-match"; + public static final String FUNCTION_STRING_EQUAL_IGNORE = "urn:oasis:names:tc:xacml:3.0:function:string-equal-ignore-case"; + public static final String INTEGER_DATATYPE = "http://www.w3.org/2001/XMLSchema#integer"; + public static final String BOOLEAN_DATATYPE = "http://www.w3.org/2001/XMLSchema#boolean"; + public static final String STRING_DATATYPE = "http://www.w3.org/2001/XMLSchema#string"; + public static final String URI_DATATYPE = "http://www.w3.org/2001/XMLSchema#anyURI"; + public static final String RULE_VARIABLE = "var:"; + public static final String EMPTY_STRING = ""; + + private static HtmlProcessor htmlProcessor; + + private static File policyFile; + + public static JSONObject DescribePolicy(final File policyFile) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + HumanPolicyComponent.policyFile = policyFile; + return humanPolicyLayout(); + + } + + private static JSONObject humanPolicyLayout() { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + try { + String html = processPolicy(); + JSONObject result = new JSONObject(); + result.put("html", html); + return result; + //ByteArrayInputStream is = new ByteArrayInputStream(html.getBytes(StandardCharsets.UTF_8)); + + } catch (IllegalArgumentException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "cannot build html area por policy", e); + /*AdminNotification.warn("An error has occurred. Cannot describe this policy: " + + e.getMessage());*/ + } + return null; + } + + private static String processPolicy() throws IllegalArgumentException { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + FileInputStream pIS = null; + try { + pIS = new FileInputStream(policyFile); + Object policy = XACMLPolicyScanner.readPolicy(pIS); + if (policy == null) + throw new IllegalArgumentException("Policy File " + policyFile.getName() + + " cannot be unmarshalled"); + + HumanPolicyComponent.htmlProcessor = + new HtmlProcessor(HumanPolicyComponent.policyFile, policy); + + Path policyPath = FileSystems.getDefault().getPath(policyFile.getAbsolutePath()); + XACMLPolicyScanner xacmlScanner = new XACMLPolicyScanner(policyPath, htmlProcessor); + xacmlScanner.scan(); + String html = htmlProcessor.html(); + if (LOGGER.isDebugEnabled()) + LOGGER.debug(policyPath + System.lineSeparator() + html); + + return html; + + } catch (Exception e) { + String msg = "Exception reading policy: " + policyFile.getAbsolutePath() + + ": " + e.getMessage(); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + msg, e); + throw new IllegalArgumentException(msg); + } finally { + if (pIS != null) { + try { + pIS.close(); + } catch (IOException e) { + LOGGER.warn(e.getMessage(), e); + } + } + } + } + +} + +class HtmlProcessor extends SimpleCallback { + + private static final Logger LOGGER = FlexLogger.getLogger(HtmlProcessor.class); + + private static Map function2human; + static { + function2human = new HashMap(); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL, "equal"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_EQUAL_IGNORE, "equal"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_ONE_AND_ONLY, "one-and-only"); + function2human.put(HumanPolicyComponent.FUNCTION_STRING_REGEX_MATCH, "matching regular expression"); + function2human.put(HumanPolicyComponent.FUNTION_INTEGER_ONE_AND_ONLY, "one-and-only"); + } + + private static Map combiningAlgo2human; + static { + combiningAlgo2human = new HashMap(); + combiningAlgo2human.put("deny-overrides", "to deny if any $placeholder$ below evaluates to deny"); + combiningAlgo2human.put("permit-overrides", "to permit if any $placeholder$ below evaluates to permit"); + + combiningAlgo2human.put("ordered-deny-overrides", "to deny if any $placeholder$ below evaluates to deny"); + combiningAlgo2human.put("ordered-permit-overrides", "to permit if any $placeholder$ below evaluates to permit"); + combiningAlgo2human.put("deny-unless-permit", "to permit if any $placeholder$ below evaluates to deny and not indeterminate"); + + combiningAlgo2human.put("permit-unless-deny", "to deny if any $placeholder$ below evaluates to is permit and not indeterminate"); + combiningAlgo2human.put("first-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); + combiningAlgo2human.put("only-one-applicable", "to honour the result of the first successfully evaluated $placeholder$ in order"); + } + + private Map attributeIdentifiersMap = new HashMap(); + + private final StringWriter stringWriter = new StringWriter(); + private final PrintWriter htmlOut = new PrintWriter(stringWriter); + private final String policyName; + private final Object rootPolicyObject; + + public HtmlProcessor(File policyFile, Object policyObject) + throws IllegalArgumentException { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + if (policyFile == null) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Null Policy File"); + throw new IllegalArgumentException("Null Policy File"); + } + + if (!policyFile.exists() || !policyFile.canRead()) { + String msg = "Can't access " + policyFile.getAbsolutePath(); + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + msg); + throw new IllegalArgumentException(msg); + } + + if (policyObject == null || + (!(policyObject instanceof PolicySetType) && !(policyObject instanceof PolicyType))) { + String msg = "Invalid unmarshalled object: " + policyObject; + LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID + msg); + throw new IllegalArgumentException(msg); + } + + this.policyName = FilenameUtils.removeExtension(policyFile.getName()); + this.rootPolicyObject = policyObject; + + String version = "-"; + if (policyObject instanceof PolicyType) { + PolicyType policy = (PolicyType) policyObject; + version = policy.getVersion(); + htmlOut.println("

Policy: " + policyName + + " (version " + version + ")

"); + + } else { + PolicySetType policySet = (PolicySetType) policyObject; + version = policySet.getVersion(); + htmlOut.println("

Policy Set: " + policyName + + " (v" + version + ")

"); + } + + htmlOut.println("

Location: " + policyFile.getPath() + "

"); + htmlOut.println("
"); + + if (rootPolicyObject instanceof PolicySetType) { + if (policyName.startsWith("Config_")) { + htmlOut.println("

This is a config policy set.

"); + } else if (policyName.startsWith("Action_")) { + htmlOut.println("

This is an action policy set.

"); + } + htmlOut.println("
"); + } else { + if (policyName.startsWith("Config_")) { + htmlOut.println("

This is a config policy.

"); + } else if (policyName.startsWith("Action_")) { + htmlOut.println("

This is an action policy.

"); + } + htmlOut.println("
    "); + } + } + + /** + * @return the attributeIdentifiersMap + */ + public Map getAttributeIdentifiersMap() { + return attributeIdentifiersMap; + } + + @Override + public void onFinishScan(Object root) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + if (rootPolicyObject instanceof PolicySetType) { + htmlOut.println("
"); + } else { + htmlOut.println(""); + } + + htmlOut.println("
"); + + htmlOut.println("

Attribute Table:

"); + + htmlOut.println(""); + htmlOut.println(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.println(""); + for(Map.Entry entry : this.attributeIdentifiersMap.entrySet()){ + AttributeIdentifiers value = entry.getValue(); + htmlOut.println(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.print(""); + htmlOut.println(""); + } + htmlOut.println("
CategoryTypeIdentifier
" + value.category + "" + value.type + "" + value.id + "
"); + + htmlOut.println("

"); + + // Not necessary for the user, uncomment if desired at some point + // writeRawXACML() + + super.onFinishScan(root); + } + + @SuppressWarnings("unused") + private void writeRawXACML() { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + htmlOut.println("
"); + htmlOut.println("

Raw XACML:

"); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + if (rootPolicyObject instanceof PolicySetType) { + XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicySetType) rootPolicyObject); + } else if (rootPolicyObject instanceof PolicyType) { + XACMLPolicyWriterWithPapNotify.writePolicyFile(bos, (PolicyType) rootPolicyObject); + } + + String xacml = bos.toString(); + xacml = xacml.replaceAll("<", "<"); + xacml = xacml.replaceAll(">", ">"); + htmlOut.println("
");
+		htmlOut.println(xacml);
+		htmlOut.println("
"); + } + + @Override + public CallbackResult onPreVisitPolicySet(PolicySetType parent, PolicySetType policySet) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policySet.getDescription(); + if (description != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + + " Description: " + policySet.getDescription()); + + if (parent == null) // root + policySet(policySet, "dl"); + else + policySet(policySet, "li"); + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) + htmlOut.println("
    "); + + return super.onPreVisitPolicySet(parent, policySet); + } + + @Override + public CallbackResult onPostVisitPolicySet(PolicySetType parent, PolicySetType policySet) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + " Version: " + policySet.getVersion()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policySet.getDescription(); + if (description != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId() + + " Description: " + policySet.getDescription()); + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) + htmlOut.println("
"); + + htmlOut.println("

"); + + return super.onPostVisitPolicySet(parent, policySet); + } + + public void policySet(PolicySetType policySet, String htmlListElement) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policySet.getPolicySetId()); + + String combiningAlgorithm = "-"; + String id = "-"; + String version = "-"; + + + if (policySet.getPolicyCombiningAlgId() != null) + combiningAlgorithm = extractLastIdentifier(policySet.getPolicyCombiningAlgId(), ":"); + + if (policySet.getPolicySetId() != null) + id = extractLastIdentifier(policySet.getPolicySetId(), ":"); + + if (policySet.getVersion() != null) + version = policySet.getVersion(); + + + htmlOut.println("<" + htmlListElement + ">Policy Set ID: " + id + + " (v" + version + ") " + ""); + + if (policySet.getTarget() == null || + policySet.getTarget().getAnyOf() == null || + policySet.getTarget().getAnyOf().size() <= 0) { + htmlOut.println("

This policy set applies to all requests.

"); + } else { + htmlOut.print("

"); + htmlOut.print("This policy set applies to requests with attributes "); + + List anyOf_s = policySet.getTarget().getAnyOf(); + target(anyOf_s); + htmlOut.println(".

"); + } + + if (policySet.getPolicySetOrPolicyOrPolicySetIdReference() != null && + policySet.getPolicySetOrPolicyOrPolicySetIdReference().size() > 0) { + String algoDesc = combiningAlgo2human.get(combiningAlgorithm); + if (algoDesc != null) { + algoDesc = algoDesc.replace("$placeholder$", "policy") + " (" + "" + combiningAlgorithm + ")"; + } else { + algoDesc = combiningAlgorithm; + } + + htmlOut.println("

The result is " + algoDesc + ":

"); + } + } + + @Override + public CallbackResult onPreVisitPolicy(PolicySetType parent, PolicyType policy) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + String description = policy.getDescription(); + if (description != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + + " Description: " + policy.getDescription()); + + policy(policy); + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) + htmlOut.println("
    "); + + return super.onPreVisitPolicy(parent, policy); + } + + @Override + public CallbackResult onPostVisitPolicy(PolicySetType parent, PolicyType policy) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + " Version: " + policy.getVersion()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("PolicySet: " + policy.getPolicyId() + + "Parent PolicySet: " + parent.getPolicySetId() + " Version: " + parent.getVersion()); + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) + htmlOut.println("
"); + + htmlOut.println("

"); + return super.onPostVisitPolicy(parent, policy); + } + + public void policy(PolicyType policy) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("Policy: " + policy.getPolicyId()); + + String combiningAlgorithm = "-"; + String id = "-"; + String version = "-"; + + + if (policy.getRuleCombiningAlgId() != null) + combiningAlgorithm = extractLastIdentifier(policy.getRuleCombiningAlgId(), ":"); + + if (policy.getPolicyId() != null) + id = extractLastIdentifier(policy.getPolicyId(), ":"); + + if (policy.getVersion() != null) + version = policy.getVersion(); + + htmlOut.println("
  • Policy ID: " + id + + " (v" + version + ") " + "
  • "); + + if (policy.getTarget() == null || + policy.getTarget().getAnyOf() == null || + policy.getTarget().getAnyOf().size() <= 0) { + htmlOut.println("

    This policy applies to all requests.

    "); + } else { + htmlOut.print("

    "); + htmlOut.print("This policy applies to requests with attributes "); + + List anyOf_s = policy.getTarget().getAnyOf(); + target(anyOf_s); + htmlOut.println(".

    "); + } + + if (policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() != null && + policy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().size() > 0) { + String algoDesc = combiningAlgo2human.get(combiningAlgorithm); + if (algoDesc != null) { + algoDesc = algoDesc.replace("$placeholder$", "rule") + " (" + combiningAlgorithm + ")"; + } else { + algoDesc = combiningAlgorithm; + } + htmlOut.println("

    The result is " + algoDesc + ":

    "); + } + } + + + @Override + public CallbackResult onPreVisitRule(PolicyType parent, RuleType rule) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("Rule: " + rule.getRuleId()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + + String description = rule.getDescription(); + if (description != null && LOGGER.isTraceEnabled()) { + LOGGER.trace("Rule: " + rule.getRuleId() + + " Description: " + rule.getDescription()); + } + + rule(rule); + + return super.onPreVisitRule(parent, rule); + } + + @Override + public CallbackResult onPostVisitRule(PolicyType parent, RuleType rule) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("Rule: " + rule.getRuleId()); + + if (parent != null && LOGGER.isTraceEnabled()) + LOGGER.trace("Parent Policy: " + parent.getPolicyId() + " Version: " + parent.getVersion()); + + return super.onPostVisitRule(parent, rule); + } + + public void rule(RuleType rule) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("Rule: " + rule.getRuleId()); + + String id = "-"; + + if (rule.getRuleId() != null) + id = extractLastIdentifier(rule.getRuleId(), ":"); + + htmlOut.println("
  • Rule ID: " + id + "
  • "); + + htmlOut.println("
    "); + + htmlOut.print("

    "); + htmlOut.print(rule.getEffect().value()); + + if (rule.getTarget() == null || + rule.getTarget().getAnyOf() == null || + rule.getTarget().getAnyOf().size() <= 0) { + htmlOut.print(" for all requests"); + } else { + List anyOf_s = rule.getTarget().getAnyOf(); + htmlOut.print(" for requests with attributes "); + target(anyOf_s); + } + + if (rule.getCondition() != null) { + htmlOut.print(" when "); + htmlOut.println(this.stringifyCondition(rule.getCondition()) + " "); + } else { + htmlOut.print(" with no conditions "); + } + + if (rule.getAdviceExpressions() != null) { + advice(rule.getAdviceExpressions()); + if (rule.getObligationExpressions() != null) + htmlOut.println(" and "); + } + + if (rule.getObligationExpressions() != null) { + obligation(rule.getObligationExpressions()); + } + + htmlOut.println("

    "); + } + + private void advice(AdviceExpressionsType adviceExpressions) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + List ae = adviceExpressions.getAdviceExpression(); + for (AdviceExpressionType expression : ae) { + htmlOut.println(" with advice (" + expression.getAdviceId() + ") on " + + expression.getAppliesTo().value() + ":" ); + htmlOut.println("
      "); + List assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + processAttributeAssignments(assignments); + } + htmlOut.println("
    "); + } + } + + private void obligation(ObligationExpressionsType obligationExpressions) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + List oe = obligationExpressions.getObligationExpression(); + for (ObligationExpressionType expression : oe) { + htmlOut.println(" with obligations (" + expression.getObligationId() + ") to be fullfilled on " + + expression.getFulfillOn().value() + ":" ); + htmlOut.println("
      "); + List assignments = expression.getAttributeAssignmentExpression(); + if (assignments != null) { + processAttributeAssignments(assignments); + } + htmlOut.println("
    "); + } + } + + /** + * @param assignments + */ + private void processAttributeAssignments(List assignments) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + for (AttributeAssignmentExpressionType assignment : assignments) { + String succintIdentifier = extractLastIdentifier(assignment.getCategory(), ":") + + ":" + extractLastIdentifier(assignment.getAttributeId(), ":"); + AttributeIdentifiers attributeIdentifiers = null; + if (!this.attributeIdentifiersMap.containsKey(succintIdentifier)) { + // Note Attribute Assignments do not have an Attribute Type, assume string + // but note this case is unlikely since attributeMap should have been populated + // during parsing of target and conditions, and not in this case for Advice and + // Obligations. + attributeIdentifiers = new AttributeIdentifiers(assignment.getCategory(), + "NA", + assignment.getAttributeId()); + this.attributeIdentifiersMap.put(succintIdentifier, attributeIdentifiers); + } + + htmlOut.print("
  • " + succintIdentifier + " is "); + // AttributeValueType + JAXBElement jaxbExp = assignment.getExpression(); + Object assignmentObject = jaxbExp.getValue(); + if (assignmentObject instanceof AttributeValueType) { + AttributeValueType avt = (AttributeValueType) assignmentObject; + if (attributeIdentifiers != null) { + attributeIdentifiers.type = avt.getDataType(); + } + int numContent = avt.getContent().size(); + int countContent = 0; + for (Object c: avt.getContent()) { + countContent++; + htmlOut.print("" + c + ""); + if (countContent < numContent) + htmlOut.print(" or "); + } + htmlOut.println("
  • "); + } else if (assignmentObject instanceof AttributeDesignatorType) { + htmlOut.println("NA"); + } else if (assignmentObject instanceof AttributeSelectorType) { + htmlOut.println("NA"); + } else if (assignmentObject instanceof ApplyType) { + htmlOut.println("NA"); + } else { + htmlOut.println("Unexpected"); + } + } + } + + /** + * + * @param anyOfList + */ + public void target(List anyOfList) { + if (LOGGER.isTraceEnabled()) + LOGGER.trace("ENTER"); + + if (anyOfList != null) { + Iterator iterAnyOf = anyOfList.iterator(); + String targetInHuman = ""; + while (iterAnyOf.hasNext()) { + AnyOfType anyOf = iterAnyOf.next(); + List allOfList = anyOf.getAllOf(); + if (allOfList != null) { + Iterator iterAllOf = allOfList.iterator(); + while (iterAllOf.hasNext()) { + AllOfType allOf = iterAllOf.next(); + List matchList = allOf.getMatch(); + if (matchList != null) { + Iterator iterMatch = matchList.iterator(); + if (matchList.size() > 1) + targetInHuman += "("; + while (iterMatch.hasNext()) { + MatchType match = iterMatch.next(); + // + // Finally down to the actual attribute + // + StdAttribute attribute = null; + AttributeValueType value = match.getAttributeValue(); + String attributeDataType = null; + if (match.getAttributeDesignator() != null && value != null) { + AttributeDesignatorType designator = match.getAttributeDesignator(); + attribute = new StdAttribute(new IdentifierImpl(designator.getCategory()), + new IdentifierImpl(designator.getAttributeId()), + new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), + designator.getIssuer(), + false); + attributeDataType = designator.getDataType(); + } else if (match.getAttributeSelector() != null && value != null) { + AttributeSelectorType selector = match.getAttributeSelector(); + attribute = new StdAttribute(new IdentifierImpl(selector.getCategory()), + new IdentifierImpl(selector.getContextSelectorId()), + new StdAttributeValue>(new IdentifierImpl(value.getDataType()), value.getContent()), + null, + false); + attributeDataType = selector.getDataType(); + } else { + LOGGER.warn("NULL designator/selector or value for match."); + attributeDataType = "NA"; + } + + String functionName = getHumanFunction(match.getMatchId()); + + String succintIdentifier = extractLastIdentifier(attribute.getCategory().stringValue(), ":") + + ":" + extractLastIdentifier(attribute.getAttributeId().stringValue(), ":"); + AttributeIdentifiers ai = new AttributeIdentifiers(attribute.getCategory().stringValue(), + attributeDataType, + attribute.getAttributeId().stringValue()); + this.attributeIdentifiersMap.put(succintIdentifier,ai); + + targetInHuman += "" + succintIdentifier + " " + functionName + " "; + + int numAttributes = attribute.getValues().size(); + int count = 0; + for (AttributeValue v: attribute.getValues()) { + count++; + if (v.getValue() instanceof Collection) { + Collection value_s = (Collection) v.getValue(); + int numValues = value_s.size(); + int countValues = 0; + for (Object o : value_s) { + countValues++; + targetInHuman += " " + o + ""; + if (countValues < numValues) { + targetInHuman += ", or"; + } + } + } else { + targetInHuman += " " + v.getValue() + ""; + if (count < numAttributes) { + targetInHuman += ", or "; + } + } + } + + if (iterMatch.hasNext()) { + targetInHuman += " and "; + } + } // end iterMatch + if (matchList.size() > 1) { + targetInHuman += ")"; + } + } + if (iterAllOf.hasNext()) { + targetInHuman += " or "; + } + } // end iterAllOf + } + if (iterAnyOf.hasNext()) { + targetInHuman = "(" + targetInHuman + ")" + " or "; + } else { + if (anyOfList.size() > 1) { + targetInHuman += ")"; + } + } + } // end iterAnyOf + htmlOut.println(targetInHuman); + } + } + + private String getHumanFunction(String matchId) { + if (HtmlProcessor.function2human.containsKey(matchId)) { + return HtmlProcessor.function2human.get(matchId); + } + + FunctionDefinition function = PolicyController.getFunctionIDMap().get(matchId); + String functionName = function.getShortname(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + + ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); + } + + return extractLastIdentifier(removePrimitives(functionName), ":"); + } + + public String html() { + this.htmlOut.flush(); + return this.stringWriter.toString(); + } + + private String extractLastIdentifier(String in, String separator) { + int lastIndex = in.lastIndexOf(separator); + if (lastIndex < 0) + return in; + else + return in.substring(lastIndex+1); + } + + private String removePrimitives(String in) { + in = in.replace("string-", ""); + in = in.replace("integer-", ""); + in = in.replace("double-", ""); + in = in.replace("boolean-", ""); + return in; + } + + private String stringifyCondition(ConditionType condition) { + if (condition.getExpression() == null) { + return ""; + } + + return stringifyExpression(condition.getExpression().getValue()); + } + + private String stringifyExpression(Object expression) { + if (expression instanceof ApplyType) { + ApplyType apply = (ApplyType) expression; + FunctionDefinition function = PolicyController.getFunctionIDMap().get(apply.getFunctionId()); + String functionName = function.getShortname(); + + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + + ": #args[" + function.getArgLb() + "," + function.getArgUb() +"]"); + } + + if (functionName.contains("one-and-only")) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("one-and-only found: " + functionName); + } + + List> exps = apply.getExpression(); + if (exps == null || exps.size() == 0) + return ""; + else { + String forResult = ""; + for (JAXBElement e : exps) { + Object v = e.getValue(); + if (LOGGER.isDebugEnabled()) { + LOGGER.debug("one-and-only children: " + v); + } + if (v != null) { + // C: return stringifyExpression(v, result); + forResult += stringifyExpression(v); + } + } + return forResult; + } + } + + final int numExpr = (apply.getExpression() == null) ? -1 : apply.getExpression().size(); + if (numExpr <= 0) { + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + " 0 expressions: " + numExpr); + } + return ""; + } else if (numExpr == 1) { + // eg: not + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + " 1 expression: " + numExpr); + } + String applySubresult = ""; + for (JAXBElement e : apply.getExpression()) { + Object v = e.getValue(); + if (v != null) { + applySubresult += this.stringifyExpression(e.getValue()); + } + } + return " " + removePrimitives(functionName) + " (" + applySubresult + ")"; + } else { + // > 1 arguments + if (LOGGER.isDebugEnabled()) { + LOGGER.debug(functionName + " > 1 expressions: " + numExpr); + } + String applySubresult = ""; + int exprCount = 0; + for (JAXBElement e : apply.getExpression()) { + exprCount++; + Object ev = e.getValue(); + if (ev != null) { + if (ev instanceof ApplyType) { + if (((ApplyType) ev).getFunctionId().contains("one-and-only")) { + applySubresult += this.stringifyExpression(e.getValue()); + } else { + applySubresult += "(" + this.stringifyExpression(e.getValue()) + ")"; + } + } else { + applySubresult += this.stringifyExpression(e.getValue()); + } + + if (exprCount < numExpr) { + applySubresult += " " + removePrimitives(functionName) + " "; + } + } + } + return applySubresult; + } + } + if (expression instanceof AttributeDesignatorType) { + AttributeDesignatorType adt = (AttributeDesignatorType) expression; + + String succintIdentifier = extractLastIdentifier(adt.getCategory(), ":") + + ":" + extractLastIdentifier(adt.getAttributeId(), ":"); + AttributeIdentifiers ai = new AttributeIdentifiers(adt.getCategory(), + adt.getDataType(), + adt.getAttributeId()); + this.attributeIdentifiersMap.put(succintIdentifier,ai); + + return "" + succintIdentifier + ""; + } + if (expression instanceof AttributeSelectorType) { + AttributeSelectorType ast = (AttributeSelectorType) expression; + + String attrName = ast.getPath(); + if (attrName == null || (attrName.length() == 0)) { + return ""; + } + + String textSelector = "/text()"; + if (attrName.endsWith(textSelector)) { + attrName = attrName.substring(0, attrName.length() - textSelector.length()); + } + + attrName = extractLastIdentifier(attrName, "/"); + attrName = extractLastIdentifier(attrName, ":"); + return " " + attrName; + } + if (expression instanceof AttributeValueType) { + AttributeValueType avt = (AttributeValueType) expression; + List content = avt.getContent(); + String value_s = ""; + for (Object o: content) { + value_s += " " + o.toString(); + } + return " " + value_s; + } + if (expression instanceof VariableReferenceType) { + // + // Really unknown - the variable may or may not have been defined + // + return " VARIABLEREF-NOT-HANDLED"; + } else { + throw new IllegalArgumentException("Unexpected input expression"); + } + } +} + + +class AttributeIdentifiers { + public final String category; + public String type; + public final String id; + + public AttributeIdentifiers(String category, String type, String id) { + this.category = category; + this.type = type; + this.id = id; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java new file mode 100644 index 000000000..30a49a1ae --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/components/PolicyImportWindow.java @@ -0,0 +1,167 @@ +/*- + * ============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.components; + + +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.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Set; + +import org.apache.commons.compress.archivers.tar.TarArchiveEntry; +import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; +import org.apache.commons.io.IOUtils; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + + + +public class PolicyImportWindow{ + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyImportWindow.class); + private Path newfile = null; + private boolean succeeded = false; + private Boolean superadmin = false; + private ArrayList xacmlFiles = new ArrayList(); + private static FileOutputStream outputFile; + /** + * The constructor should first build the main layout, set the + * composition root and then do any custom initialization. + * + * The constructor will not be automatically regenerated by the + * visual editor. + */ + + public OutputStream receiveUpload(String filename, String mimeType) { + + // + // Create its new full path + // + this.newfile = null; + // + // Does it already exist? + // + if (Files.exists(this.newfile)) { + return null; + } + // + // Try to create the output stream + // + try { + return new FileOutputStream(this.newfile.toFile()); + } catch (FileNotFoundException e) { + LOGGER.error("Failed to create uploaded file", e); + } + return null; + } + + public void Upload(){ + TarArchiveEntry entry = null; + TarArchiveInputStream extractFile = null; + try { + extractFile = new TarArchiveInputStream (new FileInputStream(this.newfile.toFile())); + } catch (FileNotFoundException e1) { + e1.printStackTrace(); + } + //Create a loop to read every single entry in TAR file + try { + 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); + } + } + } catch (IOException e) { + e.printStackTrace(); + } + + } + + //Copy files to Directorys + public static void copyFileToLocation(TarArchiveInputStream extractFile, TarArchiveEntry entry, ArrayList xacmlFiles, Set finalScopes, Boolean superadminValue ) throws IOException{ + String individualFiles = ""; + int offset = 0; + outputFile = null; + // Get the name of the file + if(superadminValue){ + individualFiles = entry.getName(); + }else{ + for(int i =0; i< finalScopes.size(); i++){ + if(entry.getName().startsWith(finalScopes.toArray()[i].toString())){ + individualFiles = entry.getName(); + } + } + } + + if(individualFiles.endsWith(".xls")){ + if(individualFiles.contains("\\")){ + individualFiles = individualFiles.replace("\\", File.separator); + }else if(individualFiles.contains("/")){ + individualFiles = individualFiles.replace("/", File.separator); + } + return; + } + + individualFiles = individualFiles.replace("/", File.separator); + individualFiles = individualFiles.replace("\\", File.separator); + + //Create the path with the entry name + + + + // Get Size of the file and create a byte array for the size + byte[] content = new byte[(int) entry.getSize()]; + + offset=0; + LOGGER.info("Size of the File is: " + entry.getSize()); + // Read file from the archive into byte array + extractFile.read(content, offset, content.length - offset); + + // 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(); + } + } + + + public Path getUploadedFile() { + if (this.succeeded) { + return this.newfile; + } + return null; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java new file mode 100644 index 000000000..b3db51df4 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/conf/HibernateSession.java @@ -0,0 +1,60 @@ +/*- + * ============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.conf; + +/* + * + * + * */ +import java.util.Properties; + +import org.hibernate.HibernateException; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.rest.jpa.SystemLogDB; + +@SuppressWarnings("deprecation") +public class HibernateSession{ + + private static SessionFactory logSessionFactory; + + static { + try { + Properties prop= new Properties(); + prop.setProperty("hibernate.connection.url", PolicyController.logdbUrl); + prop.setProperty("hibernate.connection.username", PolicyController.logdbUserName); + prop.setProperty("hibernate.connection.password", PolicyController.logdbPassword); + prop.setProperty("dialect", PolicyController.logdbDialect); + prop.setProperty("hibernate.connection.driver_class", PolicyController.logdbDriver); + prop.setProperty("show_sql", "false"); + logSessionFactory = new Configuration().addPackage("org.openecomp.policy.*").addProperties(prop) + .addAnnotatedClass(SystemLogDB.class).buildSessionFactory(); + } catch (Throwable ex) { + throw new ExceptionInInitializerError(ex); + } + } + public static Session getSession() throws HibernateException { + return logSessionFactory.openSession(); + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java new file mode 100644 index 000000000..2e555f254 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/ActionPolicyController.java @@ -0,0 +1,266 @@ +/*- + * ============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.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + + +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); + + public ActionPolicyController(){} + + private ArrayList attributeList; + protected LinkedList ruleAlgoirthmTracker; + public static final String PERFORMER_ATTRIBUTEID = "performer"; + protected Map performer = new HashMap(); + private ArrayList ruleAlgorithmList; + + public void prePopulateActionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + 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.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("key", attributeId); + attribute.put("value", 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) { + 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/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AdminTabController.java new file mode 100644 index 000000000..ee5ed7279 --- /dev/null +++ b/POLICY-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.rest.dao.CommonClassDao; +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 + CommonClassDao commonClassDao; + + + + @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(commonClassDao.getData(GlobalRoleSettings.class))); + 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"); + commonClassDao.update(globalRole); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); + 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/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java new file mode 100644 index 000000000..77bcea6ef --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/AutoPushController.java @@ -0,0 +1,355 @@ +/*- + * ============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.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.net.URI; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +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 javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.policy.model.PDPPolicyContainer; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.adapter.AutoPushTabAdapter; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; +import org.openecomp.policy.xacml.std.pap.StdPDPGroup; +import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; +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.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +@Controller +@RequestMapping({"/"}) +public class AutoPushController extends RestrictedBaseController{ + + private static final Logger logger = FlexLogger.getLogger(AutoPushController.class); + + @Autowired + CommonClassDao commonClassDao; + + private PDPGroupContainer container; + protected List groups = Collections.synchronizedList(new ArrayList()); + + private static PDPPolicyContainer policyContainer; + Set selectedPolicies; + + private List data; + + 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{ + Set scopes = null; + List roles = null; + data = null; + String userId = UserUtils.getUserSession(request).getOrgUserId(); + Map model = new HashMap(); + ObjectMapper mapper = new ObjectMapper(); + List userRoles = PolicyController.getRoles(userId); + roles = new ArrayList(); + scopes = new HashSet(); + for(Object role: userRoles){ + Roles userRole = (Roles) role; + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest") ) { + data = commonClassDao.getData(PolicyVersion.class); + }else{ + List filterdatas = commonClassDao.getData(PolicyVersion.class); + for(Object filter : filterdatas){ + PolicyVersion filterdata = (PolicyVersion) filter; + String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); + if(scopes.contains(scopeName)){ + data.add(filterdata); + } + } + } + model.put("policydatas", mapper.writeValueAsString(data)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } + + @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; + String policyName = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml"; + selectedPoliciesInUI.add(policyName); + } + + for (Object pdpDestinationGroupId : selectedPDPS) { + Set currentPoliciesInGroup = new HashSet(); + Set selectedPolicies = new HashSet(); + for (String policyId : selectedPoliciesInUI) { + logger.debug("Handlepolicies..." + pdpDestinationGroupId + policyId); + + // + // Get the current selection + String selectedItem = policyId; + // + assert (selectedItem != 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.replace(File.separator, "."); + String id = name; + if (id.endsWith(".xml")) { + id = id.replace(".xml", ""); + id = id.substring(0, id.lastIndexOf(".")); + } + + // Default policy to be Root policy; user can change to deferred + // later + + StdPDPPolicy selectedPolicy = null; + String dbCheckName = name; + if(dbCheckName.contains("Config_")){ + dbCheckName = dbCheckName.replace(".Config_", ":Config_"); + }else if(dbCheckName.contains("Action_")){ + dbCheckName = dbCheckName.replace(".Action_", ":Action_"); + }else if(dbCheckName.contains("Decision_")){ + dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); + } + PolicyController controller = new PolicyController(); + String[] split = dbCheckName.split(":"); + String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; + System.out.println(query); + List queryData = controller.getDataByQuery(query); + PolicyEntity policyEntity = (PolicyEntity) queryData.get(0); + File temp = new File(name); + BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); + bw.write(policyEntity.getPolicyData()); + bw.close(); + URI selectedURI = temp.toURI(); + try { + // + // Create the policy + selectedPolicy = new StdPDPPolicy(name, true, id, selectedURI); + } catch (IOException e) { + logger.error("Unable to create policy '" + name + "': "+ 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); + } + temp.delete(); + } + 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; + } + + @SuppressWarnings("unchecked") + @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/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java new file mode 100644 index 000000000..786e17a16 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSParamController.java @@ -0,0 +1,508 @@ +/*- + * ============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.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.bind.JAXBElement; + +import org.json.JSONObject; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.BRMSParamTemplate; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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 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 CommonClassDao commonClassDao; + + @Autowired + private CreateBRMSParamController(CommonClassDao commonClassDao){ + CreateBRMSParamController.commonClassDao = commonClassDao; + } + + public CreateBRMSParamController(){} + protected PolicyRestAdapter policyAdapter = null; + private ArrayList attributeList; + + private HashMap dynamicLayoutMap; + + + @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) { + List datas = commonClassDao.getData(BRMSParamTemplate.class); + for (Object data: datas){ + BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) data; + 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 void createField(String caption, String type) { + dynamicLayoutMap.put(caption, type); + } + + + @SuppressWarnings("unchecked") + public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + 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); + 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); + }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){ + ArrayList dependencies = new ArrayList(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); + if(dependencies.contains("")){ + dependencies.remove(""); + } + policyAdapter.setBrmsDependency(dependencies); + }else if(attributeAssignment.getAttributeId().startsWith("controller:")){ + policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); + } + } + policyAdapter.setAttributes(attributeList); + } + paramUIGenerate(policyAdapter, entity); + // 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(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + String data = entity.getConfigurationData().getConfigBody(); + if(data != null){ + try { + String params = ""; + Boolean flag = false; + Boolean comment = false; + for (String line : data.split("\n")) { + 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") && line.contains(".Params\"")) { + params = params + line; + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = params.substring(params.indexOf(".Params\"")+ 8); + params = params.replaceAll("\\s+", "").replace("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 (Exception e) { + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage()); + } + } + + } + + // set View Rule + @SuppressWarnings("unchecked") + @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()); + PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.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; + } + + 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 \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".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; + // Expand the body. + Map copyMap=new HashMap<>(); + copyMap.putAll((Map) policyData.getRuleData()); + copyMap.put("policyName", policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()); + copyMap.put("policyScope", policyData.getDomainDir().replace("\\", ".")); + copyMap.put("policyVersion", "1"); + //Finding all the keys in the Map data-structure. + Set keySet= copyMap.keySet(); + Iterator iterator = keySet.iterator(); + Pattern p; + Matcher m; + while(iterator.hasNext()) { + //Converting the first character of the key into a lower case. + String input= iterator.next(); + String output = Character.toLowerCase(input.charAt(0)) + + (input.length() > 1 ? input.substring(1) : ""); + //Searching for a pattern in the String using the key. + p=Pattern.compile("\\$\\{"+output+"\\}"); + m=p.matcher(body); + //Replacing the value with the inputs provided by the user in the editor. + body=m.replaceAll(copyMap.get(input)); + } + 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/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java new file mode 100644 index 000000000..381673ca5 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateBRMSRawController.java @@ -0,0 +1,173 @@ +/*- + * ============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.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +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; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.PolicyEntity; + +public class CreateBRMSRawController{ + + private static final Logger logger = FlexLogger.getLogger(CreateBRMSRawController.class); + + protected PolicyRestAdapter policyAdapter = null; + private ArrayList attributeList; + + + @SuppressWarnings("unchecked") + public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + 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); + 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); + }else if(attributeAssignment.getAttributeId().startsWith("dependencies:")){ + ArrayList dependencies = new ArrayList(Arrays.asList(attributeAssignment.getAttributeId().replace("dependencies:", "").split(","))); + if(dependencies.contains("")){ + dependencies.remove(""); + } + policyAdapter.setBrmsDependency(dependencies); + }else if(attributeAssignment.getAttributeId().startsWith("controller:")){ + policyAdapter.setBrmsController(attributeAssignment.getAttributeId().replace("controller:", "")); + } + } + policyAdapter.setAttributes(attributeList); + } + // Get the target data under policy. + policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); + 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; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java new file mode 100644 index 000000000..d75231ef0 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopFaultController.java @@ -0,0 +1,696 @@ +/*- + * ============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.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import org.openecomp.policy.rest.adapter.ClosedLoopFaultBody; +import org.openecomp.policy.rest.adapter.ClosedLoopFaultTriggerUISignatures; +import org.openecomp.policy.rest.adapter.ClosedLoopSignatures; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.EcompName; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.policy.rest.jpa.VarbindDictionary; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +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 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{ + + protected PolicyRestAdapter policyAdapter = null; + + + private static CommonClassDao commonclassdao; + + @Autowired + private CreateClosedLoopFaultController(CommonClassDao commonclassdao){ + CreateClosedLoopFaultController.commonclassdao = commonclassdao; + } + + public CreateClosedLoopFaultController(){} + + public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) throws Exception{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + 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); + + 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); + return policyData; + } + + + @SuppressWarnings("unchecked") + 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; + } + + + 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.startsWith("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; + } + + @SuppressWarnings("unchecked") + 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 = null; + try{ + varbindId = (VarbindDictionary) commonclassdao.getEntityItem(VarbindDictionary.class, "varbindName", attrib); + return varbindId.getVarbindOID(); + }catch(Exception e){ + return attrib; + } + } + + + //connect traps data set to JSON Body as String + @SuppressWarnings({ "unchecked", "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 = ""; + String connectTrap1 = ""; + String trapCount1 = ""; + String operatorBox = ""; + String connectTrap2 = ""; + String trapCount2 = ""; + if(((LinkedHashMap) object).keySet().contains("notBox")){ + notBox = ((LinkedHashMap) object).get("notBox").toString(); + } + if(((LinkedHashMap) object).get("connectTrap1") != null){ + connectTrap1 = ((LinkedHashMap) object).get("connectTrap1").toString(); + } + if(((LinkedHashMap) object).get("trapCount1") != null){ + trapCount1 = ((LinkedHashMap) object).get("trapCount1").toString(); + } + if(((LinkedHashMap) object).get("operatorBox") != null){ + operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); + } + if(((LinkedHashMap) object).get("connectTrap2") != null){ + connectTrap2 = ((LinkedHashMap) object).get("connectTrap2").toString(); + } + if(((LinkedHashMap) object).get("trapCount2") != null){ + 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 + @SuppressWarnings({ "rawtypes", "unchecked" }) + 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.startsWith("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 = ""; + String trigger1 = ""; + String operatorBox = ""; + String trigger2 = ""; + if(((LinkedHashMap) object).keySet().contains("notBox")){ + notBox = ((LinkedHashMap) object).get("notBox").toString(); + } + if(((LinkedHashMap) object).get("trigger1") != null){ + trigger1 = ((LinkedHashMap) object).get("trigger1").toString(); + } + if(((LinkedHashMap) object).get("operatorBox") != null){ + operatorBox = ((LinkedHashMap) object).get("operatorBox").toString(); + } + if(((LinkedHashMap) object).get("trigger2") != null){ + trigger2 = ((LinkedHashMap) object).get("trigger2").toString(); + } + connectBody = notBox + "@!" + trigger1 + "@!" + operatorBox + "@!" + trigger2 + "#!"; + } + signatureBody = signatureBody + connectBody; + } + triggerBody = triggerBody + signatureBody + "?!"; + } + + return triggerBody; + } + + public void prePopulateClosedLoopFaultPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + 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.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++; + } + } + } + } + } + } + } + readClosedLoopJSONFile(policyAdapter, entity); + } + + } + + 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(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + ObjectMapper mapper = new ObjectMapper(); + try { + ClosedLoopFaultBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), 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(); + } + + return null; + } + +} + +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; + } +} + +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; + } +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java new file mode 100644 index 000000000..375866aa8 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateClosedLoopPMController.java @@ -0,0 +1,206 @@ +/*- + * ============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.IOException; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; + +import javax.json.JsonArray; +import javax.json.JsonObject; + +import org.openecomp.policy.admin.PolicyManagerServlet; +import org.openecomp.policy.rest.adapter.ClosedLoopPMBody; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.PolicyEntity; + +import com.fasterxml.jackson.databind.ObjectMapper; + +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; + +public class CreateClosedLoopPMController{ + + protected PolicyRestAdapter policyAdapter = null; + + public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + 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.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); + LinkedHashMap vertica = new LinkedHashMap<>(); + vertica.put("verticaMetrics", getVertica(value)); + policyAdapter.setVerticaMetrics(vertica); + LinkedHashMap desc = new LinkedHashMap<>(); + desc.put("policyDescription", getDescription(value)); + policyAdapter.setDescription(desc); + LinkedHashMap attributes = new LinkedHashMap<>(); + attributes.put("attributes", getAttributes(value)); + policyAdapter.setAttributeFields(attributes); + } + index++; + } + } + } + } + } + } + } + readClosedLoopJSONFile(policyAdapter, entity); + } + } + + 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 void readClosedLoopJSONFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + ObjectMapper mapper = new ObjectMapper(); + try { + ClosedLoopPMBody closedLoopBody = mapper.readValue(entity.getConfigurationData().getConfigBody(), ClosedLoopPMBody.class); + policyAdapter.setJsonBodyData(closedLoopBody); + } catch (IOException e) { + e.printStackTrace(); + } + } + + //get vertica metrics data from the table + private String getVertica(String policyName){ + String verticas = null; + JsonArray data = PolicyManagerServlet.getPolicyNames(); + for(int i=0 ; i< data.size(); i++){ + if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){ + verticas = data.getJsonObject(i).getJsonString("verticaMetrics").getString(); + return verticas; + } + } + return verticas; + } + + //get policy description from the table + private String getDescription(String policyName){ + String description = null; + JsonArray data = PolicyManagerServlet.getPolicyNames(); + for(int i=0 ; i< data.size(); i++){ + if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){ + description = data.getJsonObject(i).getJsonString("policyDescription").getString(); + return description; + } + } + return description; + } + + //get Attributes + private JsonObject getAttributes(String policyName){ + JsonObject attributes = null; + JsonArray data = PolicyManagerServlet.getPolicyNames(); + for(int i=0 ; i< data.size(); i++){ + if(policyName.equals(data.getJsonObject(i).getJsonString("serviceTypePolicyName").getString())){ + attributes = data.getJsonObject(i).getJsonObject("attributes"); + return attributes; + } + } + return attributes; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java new file mode 100644 index 000000000..570ceac31 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateDcaeMicroServiceController.java @@ -0,0 +1,1139 @@ +/*- + * ============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.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +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.Enumeration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.TreeMap; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.apache.commons.compress.utils.IOUtils; +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.fileupload.servlet.ServletFileUpload; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang.StringUtils; +import org.json.JSONArray; +import org.json.JSONObject; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.GroupPolicyScopeList; +import org.openecomp.policy.rest.jpa.MicroServiceModels; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.policy.rest.util.MSAttributeObject; +import org.openecomp.policy.rest.util.MSModelUtils; +import org.openecomp.policy.rest.util.MSModelUtils.MODEL_TYPE; +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.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.gson.Gson; + +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 CreateDcaeMicroServiceController extends RestrictedBaseController { + private static final Logger logger = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); + + private static CommonClassDao commonClassDao; + private MicroServiceModels newModel; + private String newFile; + private String directory; + private List modelList = new ArrayList(); + private List dirDependencyList = new ArrayList(); + private HashMap classMap = new HashMap(); + + @Autowired + private CreateDcaeMicroServiceController(CommonClassDao commonClassDao){ + CreateDcaeMicroServiceController.commonClassDao = commonClassDao; + } + + public CreateDcaeMicroServiceController(){} + + protected PolicyRestAdapter policyAdapter = null; + private int priorityCount; + private Map attributesListRefMap = new HashMap(); + private Map> arrayTextList = new HashMap>(); + + public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData, JsonNode root) { + + String jsonContent = null; + try{ + jsonContent = decodeContent(root.get("policyJSON")).toString(); + constructJson(policyData, jsonContent); + }catch(Exception e){ + logger.error("Error while decoding microservice content"); + } + + return policyData; + } + + private GroupPolicyScopeList getPolicyObject(String policyScope) { + GroupPolicyScopeList groupList= (GroupPolicyScopeList) commonClassDao.getEntityItem(GroupPolicyScopeList.class, "name", policyScope); + return groupList; + } + + private PolicyRestAdapter constructJson(PolicyRestAdapter policyAdapter, String jsonContent) { + ObjectWriter om = new ObjectMapper().writer(); + String json=""; + DCAEMicroServiceObject microServiceObject = new DCAEMicroServiceObject(); + MicroServiceModels returnModel = new MicroServiceModels(); + microServiceObject.setTemplateVersion(XACMLProperties.getProperty(XACMLRestProperties.TemplateVersion_MS)); + if(policyAdapter.getServiceType() !=null){ + microServiceObject.setService(policyAdapter.getServiceType()); + microServiceObject.setVersion(policyAdapter.getVersion()); + returnModel = getAttributeObject(microServiceObject.getService(), microServiceObject.getVersion()); + } + if (returnModel.getAnnotation()==null || returnModel.getAnnotation().isEmpty()){ + if(policyAdapter.getUuid()!=null){ + microServiceObject.setUuid(policyAdapter.getUuid()); + } + if(policyAdapter.getLocation()!=null){ + microServiceObject.setLocation(policyAdapter.getLocation()); + } + if(policyAdapter.getConfigName()!=null){ + microServiceObject.setConfigName(policyAdapter.getConfigName()); + } + GroupPolicyScopeList policyScopeValue = getPolicyObject(policyAdapter.getPolicyScope()); + if(policyScopeValue!=null){ + microServiceObject.setPolicyScope(policyScopeValue.getGroupList()); + } + } + + if(policyAdapter.getPolicyName()!=null){ + microServiceObject.setPolicyName(policyAdapter.getPolicyName()); + } + if(policyAdapter.getPolicyDescription()!=null){ + microServiceObject.setDescription(policyAdapter.getPolicyDescription()); + } + if (policyAdapter.getPriority()!=null){ + microServiceObject.setPriority(policyAdapter.getPriority()); + }else { + microServiceObject.setPriority("9999"); + } + + if (policyAdapter.getRiskLevel()!=null){ + microServiceObject.setRiskLevel(policyAdapter.getRiskLevel()); + } + if (policyAdapter.getRiskType()!=null){ + microServiceObject.setRiskType(policyAdapter.getRiskType()); + } + if (policyAdapter.getGuard()!=null){ + microServiceObject.setGuard(policyAdapter.getGuard()); + } + microServiceObject.setContent(jsonContent); + + try { + json = om.writeValueAsString(microServiceObject); + } catch (JsonProcessingException e) { + logger.error("Error writing out the object"); + } + System.out.println(json); + String cleanJson = cleanUPJson(json); + cleanJson = removeNullAttributes(cleanJson); + policyAdapter.setJsonBody(cleanJson); + return policyAdapter; + } + + private String removeNullAttributes(String cleanJson) { + ObjectMapper mapper = new ObjectMapper(); + + try { + JsonNode rootNode = mapper.readTree(cleanJson); + JsonNode returnNode = mapper.readTree(cleanJson); + Iterator> fieldsIterator = rootNode.fields(); + boolean remove = false; + while (fieldsIterator.hasNext()) { + Map.Entry field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value==null || value.isNull()){ + ((ObjectNode) returnNode).remove(key); + remove = true; + } + } + if (remove){ + cleanJson = returnNode.toString(); + } + } catch (IOException e) { + logger.error("Error writing out the JsonNode"); + } + return cleanJson; + } + + + private String cleanUPJson(String json) { + String cleanJson = StringUtils.replaceEach(json, new String[]{"\\\\", "\\\\\\", "\\\\\\\\"}, new String[]{"\\", "\\", "\\"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\"}, new String[]{"\\"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\", "[[", "]]"}, new String[]{"\\", "[", "]"}); + + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\"", "\\\"", "\"[{", "}]\""}, new String[]{"\"", "\"", "[{", "}]"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[{", "}]\""}, new String[]{"[{", "}]"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"{", "}\""}, new String[]{"{", "}"}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\"\"", "\"\""}, new String[]{"\"", "\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\""}, new String[]{""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\""}, new String[]{"\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"\\\\\\"}, new String[]{"\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\\\\\\\""}, new String[]{"\""}); + cleanJson = StringUtils.replaceEach(cleanJson, new String[]{"\"[", "]\""}, new String[]{"[", "]"}); + return cleanJson; + } + + 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(); + } + + 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; + } + + @RequestMapping(value={"/policyController/getDCAEMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getDCAEMSTemplateData(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); + + String jsonModel = createMicroSeriveJson(returnModel); + + 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 + ",jsonValue: " + jsonModel + "}"); + list.add(j); + out.write(list.toString()); + return null; + } + + @SuppressWarnings("unchecked") + private String createMicroSeriveJson(MicroServiceModels returnModel) { + Map attributeMap = new HashMap(); + Map refAttributeMap = new HashMap(); + String attribute = returnModel.getAttributes(); + if(attribute != null){ + attribute = attribute.trim(); + } + String refAttribute = returnModel.getRef_attributes(); + if(refAttribute != null){ + refAttribute = refAttribute.trim(); + } + String enumAttribute = returnModel.getEnumValues(); + if(enumAttribute != null){ + enumAttribute = enumAttribute.trim(); + } + if (!StringUtils.isEmpty(attribute)){ + attributeMap = convert(attribute, ","); + } + if (!StringUtils.isEmpty(refAttribute)){ + refAttributeMap = convert(refAttribute, ","); + } + + Gson gson = new Gson(); + + String subAttributes = returnModel.getSub_attributes(); + if(subAttributes != null){ + subAttributes = subAttributes.trim(); + }else{ + subAttributes = ""; + } + Map gsonObject = (Map) gson.fromJson(subAttributes, Object.class); + + JSONObject object = new JSONObject(); + JSONArray array = new JSONArray(); + + for (Entry keySet : attributeMap.entrySet()){ + array = new JSONArray(); + String value = keySet.getValue(); + if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(value); + object.put(keySet.getKey().trim(), array); + }else { + object.put(keySet.getKey().trim(), value.trim()); + } + } + + for (Entry keySet : refAttributeMap.entrySet()){ + array = new JSONArray(); + String value = keySet.getValue().split(":")[0]; + if (gsonObject.containsKey(value)){ + if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(recursiveReference(value, gsonObject, enumAttribute)); + object.put(keySet.getKey().trim(), array); + }else { + object.put(keySet.getKey().trim(), recursiveReference(value, gsonObject, enumAttribute)); + } + }else { + if (keySet.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(value.trim()); + object.put(keySet.getKey().trim(), array); + }else { + object.put(keySet.getKey().trim(), value.trim()); + } + } + } + + return object.toString(); + } + + @SuppressWarnings("unchecked") + private JSONObject recursiveReference(String name, Map subAttributeMap, String enumAttribute) { + JSONObject object = new JSONObject(); + Map map = new HashMap(); + Object returnClass = subAttributeMap.get(name); + map = (Map) returnClass; + JSONArray array = new JSONArray(); + + for( Entry m:map.entrySet()){ + String[] splitValue = m.getValue().split(":"); + array = new JSONArray(); + if (subAttributeMap.containsKey(splitValue[0])){ + if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); + object.put(m.getKey().trim(), array); + }else { + object.put(m.getKey().trim(), recursiveReference(splitValue[0], subAttributeMap, enumAttribute)); + } + } else{ + if (m.getValue().split("MANY-")[1].equalsIgnoreCase("true")){ + array.put(splitValue[0].trim()); + object.put(m.getKey().trim(), array); + }else { + object.put(m.getKey().trim(), splitValue[0].trim()); + } + } + } + + return object; + } + + + @RequestMapping(value={"/policyController/getModelServiceVersioneData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView getModelServiceVersionData(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]; + Set returnList = getVersionList(servicename); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + List list = new ArrayList<>(); + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(returnList); + JSONObject j = new JSONObject("{dcaeModelVersionData: " + responseString +"}"); + list.add(j); + out.write(list.toString()); + return null; + } + + private Set getVersionList(String name) { + MicroServiceModels workingModel = new MicroServiceModels(); + Set list = new HashSet(); + List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); + for (int i = 0; i < microServiceModelsData.size(); i++) { + workingModel = (MicroServiceModels) microServiceModelsData.get(i); + if (workingModel.getVersion()!=null){ + list.add(workingModel.getVersion()); + }else{ + list.add("Default"); + } + } + return list; + } + + private MicroServiceModels getAttributeObject(String name, String version) { + MicroServiceModels workingModel = new MicroServiceModels(); + List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName", name); + for (int i = 0; i < microServiceModelsData.size(); i++) { + workingModel = (MicroServiceModels) microServiceModelsData.get(i); + if(version != null){ + if (workingModel.getVersion()!=null){ + if (workingModel.getVersion().equals(version)){ + return workingModel; + } + }else{ + return workingModel; + } + }else{ + return workingModel; + } + + } + 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(); + } + } + + public void prePopulateDCAEMSPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + 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.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.setConfigName(value); + } + if (index == 2){ + if(value != null){ + readFile(policyAdapter, entity); + } + } + 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 = dateTTL.split("T"); + String[] parts = date[0].split("-"); + + formateDate = parts[2] + "-" + parts[1] + "-" + parts[0]; + return formateDate; + } + + public static Map convert(String str, String split) { + Map map = new HashMap(); + for(final String entry : str.split(split)) { + String[] parts = entry.split("="); + map.put(parts[0], parts[1]); + } + return map; + } + + + @SuppressWarnings("unchecked") + private void readFile(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + String policyScopeName = null; + ObjectMapper mapper = new ObjectMapper(); + try { + DCAEMicroServiceObject msBody = (DCAEMicroServiceObject) mapper.readValue(entity.getConfigurationData().getConfigBody(), DCAEMicroServiceObject.class); + policyScopeName = getPolicyScope(msBody.getPolicyScope()); + policyAdapter.setPolicyScope(policyScopeName); + + policyAdapter.setPriority(msBody.getPriority()); + + if (msBody.getVersion()!= null){ + policyAdapter.setServiceType(msBody.getService()); + policyAdapter.setVersion(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(); + } + + } + + @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){ + LinkedHashMap secondObjec = new LinkedHashMap(); + readRecursivlyJSONContent((LinkedHashMap) value, secondObjec); + for(String objKey: secondObjec.keySet()){ + data.put(key+"." +objKey, secondObjec.get(objKey)); + } + }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= commonClassDao.getData(GroupPolicyScopeList.class); + if(groupList.size() > 0){ + for(int i = 0 ; i < groupList.size() ; i ++){ + pScope = (GroupPolicyScopeList) groupList.get(i); + if (pScope.getGroupList().equals(value)){ + break; + } + } + } + return pScope.getGroupName(); + } + + //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; + } + + @RequestMapping(value={"/ms_dictionary/set_MSModelData"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void SetMSModelData(HttpServletRequest request, HttpServletResponse response) throws Exception{ + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + boolean zip = false; + for (FileItem item : items) { + if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")){ + this.newModel = new MicroServiceModels(); + try{ + File file = new File(item.getName()); + OutputStream outputStream = new FileOutputStream(file); + IOUtils.copy(item.getInputStream(), outputStream); + outputStream.close(); + this.newFile = file.toString(); + this.newModel.setModelName(this.newFile.toString().split("-v")[0]); + if (this.newFile.toString().contains("-v")){ + if (item.getName().endsWith(".zip")){ + this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".zip", "")); + zip = true; + }else { + this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".xmi", "")); + } + } + }catch(Exception e){ + logger.error("Upload error : " + e); + } + } + } + List fileList = new ArrayList();; + this.directory = "model"; + if (zip){ + extractFolder(this.newFile); + fileList = listModelFiles(this.directory); + }else { + File file = new File(this.newFile); + fileList.add(file); + } + + //Process Main Model file first + classMap = new HashMap(); + for (File file : fileList) { + if(!file.isDirectory() && file.getName().endsWith(".xmi")){ + retreiveDependency(file.toString(), true); + } + } + + modelList = createList(); + + cleanUp(this.newFile); + cleanUp(directory); + + PrintWriter out = response.getWriter(); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + ObjectMapper mapper = new ObjectMapper(); + JSONObject j = new JSONObject(); + j.put("classListDatas", modelList); + j.put("modelDatas", mapper.writeValueAsString(classMap)); + out.write(j.toString()); + } + + /* + * Unzip file and store in the model directory for processing + */ + @SuppressWarnings("rawtypes") + private void extractFolder(String zipFile ) { + int BUFFER = 2048; + File file = new File(zipFile); + + ZipFile zip; + try { + zip = new ZipFile(file); + String newPath = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); + this.directory = "model" + File.separator + zipFile.substring(0, zipFile.length() - 4); + checkZipDirectory(this.directory); + new File(newPath).mkdir(); + Enumeration zipFileEntries = zip.entries(); + + // Process each entry + while (zipFileEntries.hasMoreElements()){ + // grab a zip file entry + ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); + String currentEntry = entry.getName(); + File destFile = new File("model" + File.separator + currentEntry); + File destinationParent = destFile.getParentFile(); + + destinationParent.mkdirs(); + + if (!entry.isDirectory()){ + BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); + int currentByte; + byte data[] = new byte[BUFFER]; + FileOutputStream fos = new FileOutputStream(destFile); + BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER); + while ((currentByte = is.read(data, 0, BUFFER)) != -1) { + dest.write(data, 0, currentByte); + } + dest.flush(); + dest.close(); + is.close(); + } + + if (currentEntry.endsWith(".zip")){ + extractFolder(destFile.getAbsolutePath()); + } + } + } catch (IOException e) { + logger.error("Failed to unzip model file " + zipFile); + } + } + + private void retreiveDependency(String workingFile, Boolean modelClass) { + + MSModelUtils utils = new MSModelUtils(PolicyController.msEcompName, PolicyController.msPolicyName); + HashMap tempMap = new HashMap(); + + tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); + + classMap.putAll(tempMap); + System.out.println(tempMap); + + return; + + } + + private List listModelFiles(String directoryName) { + File directory = new File(directoryName); + List resultList = new ArrayList(); + File[] fList = directory.listFiles(); + for (File file : fList) { + if (file.isFile()) { + resultList.add(file); + } else if (file.isDirectory()) { + dirDependencyList.add(file.getName()); + resultList.addAll(listModelFiles(file.getAbsolutePath())); + } + } + return resultList; + } + + private void cleanUp(String path) { + if (path!=null){ + try { + FileUtils.forceDelete(new File(path)); + } catch (IOException e) { + logger.error("Failed to delete folder " + path); + } + } + } + + private void checkZipDirectory(String zipDirectory) { + Path path = Paths.get(zipDirectory); + + if (Files.exists(path)) { + cleanUp(zipDirectory); + } + } + + private List createList() { + List list = new ArrayList(); + for (Entry cMap : classMap.entrySet()){ + if (cMap.getValue().isPolicyTempalate()){ + list.add(cMap.getKey()); + } + + } + + if (list.isEmpty()){ + if (classMap.containsKey(this.newModel.getModelName())){ + list.add(this.newModel.getModelName()); + }else { + list.add("EMPTY"); + } + } + return list; + } + +} + +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 riskType; + public String riskLevel; + public String guard = null; + + public String getGuard() { + return guard; + } + public void setGuard(String guard) { + this.guard = guard; + } + public String getRiskType() { + return riskType; + } + public void setRiskType(String riskType) { + this.riskType = riskType; + } + public String getRiskLevel() { + return riskLevel; + } + public void setRiskLevel(String riskLevel) { + this.riskLevel = riskLevel; + } + 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/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java new file mode 100644 index 000000000..ecc39cdb6 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreateFirewallController.java @@ -0,0 +1,932 @@ +/*- + * ============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.IOException; +import java.io.PrintWriter; +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 javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.hibernate.SessionFactory; +import org.json.JSONObject; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.rest.adapter.AddressGroupJson; +import org.openecomp.policy.rest.adapter.AddressJson; +import org.openecomp.policy.rest.adapter.AddressMembers; +import org.openecomp.policy.rest.adapter.DeployNowJson; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.adapter.PrefixIPList; +import org.openecomp.policy.rest.adapter.ServiceGroupJson; +import org.openecomp.policy.rest.adapter.ServiceListJson; +import org.openecomp.policy.rest.adapter.ServiceMembers; +import org.openecomp.policy.rest.adapter.ServicesJson; +import org.openecomp.policy.rest.adapter.TagDefines; +import org.openecomp.policy.rest.adapter.Tags; +import org.openecomp.policy.rest.adapter.Term; +import org.openecomp.policy.rest.adapter.TermCollector; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.AddressGroup; +import org.openecomp.policy.rest.jpa.FWTagPicker; +import org.openecomp.policy.rest.jpa.GroupServiceList; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.policy.rest.jpa.PrefixList; +import org.openecomp.policy.rest.jpa.SecurityZone; +import org.openecomp.policy.rest.jpa.ServiceList; +import org.openecomp.policy.rest.jpa.TermList; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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.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 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); + + @Autowired + SessionFactory sessionFactory; + + private static CommonClassDao commonClassDao; + + private List tagCollectorList; + private String jsonBody; + List expandablePrefixIPList = new ArrayList(); + List expandableServicesList= new ArrayList(); + @Autowired + private CreateFirewallController(CommonClassDao commonClassDao){ + CreateFirewallController.commonClassDao = commonClassDao; + } + + public CreateFirewallController(){} + private List termCollectorList; + private ArrayList attributeList; + + + public PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter policyData){ + + termCollectorList = new ArrayList(); + tagCollectorList = new ArrayList(); + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("key").toString(); + termCollectorList.add(key); + + String tag = ((LinkedHashMap) attribute).get("value").toString(); + tagCollectorList.add(tag); + } + } + } + jsonBody = constructJson(policyData); + if (jsonBody != null || jsonBody.equalsIgnoreCase("")) { + policyData.setJsonBody(jsonBody); + + } else { + policyData.setJsonBody("{}"); + } + policyData.setJsonBody(jsonBody); + + return policyData; + } + + private List mapping(String expandableList) { + String value = new String(); + String desc = new String(); + List valueDesc= new ArrayList(); + List prefixListData = commonClassDao.getData(PrefixList.class); + for (int i = 0; i< prefixListData.size(); i++) { + PrefixList 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 = commonClassDao.getData(ServiceList.class); + for (int i = 0; i< serviceListData.size(); i++) { + serviceList = (ServiceList) serviceListData.get(i); + if (serviceList.getServiceName().equals(expandableList)) { + break; + } + } + return serviceList; + } + + private GroupServiceList mappingServiceGroup(String expandableList) { + + GroupServiceList serviceGroup=null; + List serviceGroupData = commonClassDao.getData(GroupServiceList.class); + for (int i = 0; i< serviceGroupData.size(); i++) { + serviceGroup = (GroupServiceList) serviceGroupData.get(i); + if (serviceGroup.getGroupName().equals(expandableList)) { + break; + } + } + return serviceGroup; + } + + private AddressGroup mappingAddressGroup(String expandableList) { + + AddressGroup addressGroup=null; + List addressGroupData = commonClassDao.getData(AddressGroup.class); + for (int i = 0; i< addressGroupData.size(); i++) { + addressGroup = (AddressGroup) addressGroupData.get(i); + if (addressGroup.getGroupName().equals(expandableList)) { + break; + } + } + return addressGroup; + } + + public void prePopulateFWPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = 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); + 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; + try { + //Json conversion. + String data=null; + SecurityZone jpaSecurityZone; + data = entity.getConfigurationData().getConfigBody(); + tc1 = (TermCollector)mapper.readValue(data, TermCollector.class); + List securityZoneData = commonClassDao.getData(SecurityZone.class); + for (int i = 0; i < securityZoneData.size() ; i++) { + jpaSecurityZone = (SecurityZone) securityZoneData.get(i); + if (jpaSecurityZone.getZoneValue().equals(tc1.getSecurityZoneId())){ + policyAdapter.setSecurityZone(jpaSecurityZone.getZoneName()); + break; + } + } + } + catch(Exception e) { + logger.error("Exception Caused while Retriving the JSON body data" +e); + } + + Map termTagMap=null; + + for(int i=0;i(); + String ruleName= tc1.getFirewallRuleList().get(i).getRuleName(); + String tagPickerName=tc1.getRuleToTag().get(i).getTagPickerName(); + termTagMap.put("key", ruleName); + termTagMap.put("value", tagPickerName); + attributeList.add(termTagMap); + } + 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()); + PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.class); + if(policyData.getAttributes().size() > 0){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + String key = ((LinkedHashMap) attribute).get("key").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) { + List tmList = commonClassDao.getDataById(TermList.class, "termName", id); + jpaTermList = (TermList) tmList.get(0); + 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; + } + + private String constructJson(PolicyRestAdapter policyData) { + 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; + TermCollector tc = new TermCollector(); + SecurityZone jpaSecurityZone; + List termList = new ArrayList(); + + Tags tags=null; + ListtagsList= new ArrayList(); + + TagDefines tagDefine= new TagDefines(); + List tagList=null; + ServiceListJson targetSl=null; + int i=0; + try{ + + for(String tag:tagCollectorList){ + tags= new Tags(); + List tagListData = commonClassDao.getData(FWTagPicker.class); + for(int tagCounter=0; tagCounter(); + for(String val:tagValues.split("#")) { + int index=val.indexOf(":"); + String keyToStore=val.substring(0,index); + String valueToStore=val.substring(index+1,val.length()); + + tagDefine= new TagDefines(); + tagDefine.setKey(keyToStore); + tagDefine.setValue(valueToStore); + //Add to the collection. + tagList.add(tagDefine); + + } + + } + } + tags.setTags(tagList); + tags.setTagPickerName(tag); + tags.setRuleName(termCollectorList.get(i)); + tagsList.add(tags); + i++; + } + tc.setRuleToTag(tagsList); + + 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 = commonClassDao.getData(TermList.class); + for (int j =0; j < termListData.size(); j++) { + jpaTermList = (TermList) 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.setName(srcList.substring(6,srcList.length())); + }else{ + srcListJson.setName(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.setName(destList.substring(6,destList.length())); + }else{ + destListJson.setName(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++)); + } + + List securityZoneData = commonClassDao.getData(SecurityZone.class); + for (int j =0 ; j< securityZoneData.size() ; j++){ + jpaSecurityZone = (SecurityZone) securityZoneData.get(j); + if (jpaSecurityZone.getZoneName().equals(policyData.getSecurityZone())){ + tc.setSecurityZoneId(jpaSecurityZone.getZoneValue()); + //setParentSecurityZone(jpaSecurityZone.getZoneValue());//For storing the securityZone IDs to the DB + break; + } + } + + tc.setServiceTypeId("/v0/firewall/pan"); + tc.setConfigName(policyData.getConfigName()); + + //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); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:"+prefixIP); + valueDesc = mapping(prefixIP); + if(!valueDesc.isEmpty()){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList description:"+valueDesc.get(1)); + targetAddressList.setDescription(valueDesc.get(1)); + } + + + addressMembers.setType("SUBNET"); + if(!valueDesc.isEmpty()) { + 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; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java new file mode 100644 index 000000000..9a31d7f72 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/CreatePolicyController.java @@ -0,0 +1,165 @@ +/*- + * ============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.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +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{ + + protected PolicyRestAdapter policyAdapter = null; + private ArrayList attributeList; + boolean isValidForm = false; + + 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(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + attributeList = new ArrayList(); + if (policyAdapter.getPolicyData() instanceof PolicyType) { + Object policyData = policyAdapter.getPolicyData(); + PolicyType policy = (PolicyType) policyData; + policyAdapter.setOldPolicyFileName(policyAdapter.getPolicyName()); + policyAdapter.setConfigType(entity.getConfigurationData().getConfigType()); + policyAdapter.setConfigBodyData(entity.getConfigurationData().getConfigBody()); + String policyNameValue = policyAdapter.getPolicyName().substring(policyAdapter.getPolicyName().indexOf("_") + 1); + 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("key", attributeId); + attribute.put("value", 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()); + } + } + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java new file mode 100644 index 000000000..fcde0f370 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DashboardController.java @@ -0,0 +1,420 @@ +/*- + * ============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.IOException; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +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.json.JSONObject; +import org.openecomp.policy.dao.SystemLogDbDao; +import org.openecomp.policy.model.PDPGroupContainer; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.dao.CommonClassDao; +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; + + @Autowired + CommonClassDao commonClassDao; + + 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(); + 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); + List data = commonClassDao.getDataByQuery("from PolicyEntity"); + object.put("noOfPolicy", data.size()); + object.put("noOfConnectedTrap", pdpCount); + papStatusData.add(0, object); + } + + /** + * 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", "unchecked" }) + 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", "unchecked" }) + 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/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java new file mode 100644 index 000000000..d21788e90 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/DecisionPolicyController.java @@ -0,0 +1,262 @@ +/*- + * ============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.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBElement; + +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +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 org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.jpa.PolicyEntity; + +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); + + public DecisionPolicyController(){} + + protected PolicyRestAdapter policyAdapter = null; + 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"; + + @SuppressWarnings("unchecked") + public void prePopulateDecisionPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + 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.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("key", attributeId); + attribute.put("value", 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("key", variableDefinitionType.getVariableId()); + JAXBElement attributeValueTypeElement = (JAXBElement) variableDefinitionType.getExpression(); + if (attributeValueTypeElement != null) { + AttributeValueType attributeValueType = attributeValueTypeElement.getValue(); + settings.put("value", attributeValueType.getContent().get(0).toString()); + } + decisionList.add(settings); + } else if (object instanceof RuleType) { + // get the condition data under the rule for rule Algorithms. + 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/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java new file mode 100644 index 000000000..2fcf7939b --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PDPController.java @@ -0,0 +1,292 @@ +/*- + * ============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.model.PDPGroupContainer; +import org.openecomp.portalsdk.core.controller.RestrictedBaseController; +import org.openecomp.portalsdk.core.web.support.JsonMessage; +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 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); + + 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/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java new file mode 100644 index 000000000..72dfb164b --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyController.java @@ -0,0 +1,421 @@ +/*- + * ============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.IOException; +import java.io.InputStream; +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.json.JSONObject; +import org.openecomp.policy.admin.PolicyNotificationMail; +import org.openecomp.policy.admin.RESTfulPAPEngine; +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.CommonClassDao; +import org.openecomp.policy.rest.jpa.Datatype; +import org.openecomp.policy.rest.jpa.FunctionDefinition; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.UserInfo; +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.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 CommonClassDao commonClassDao; + // Our authorization object + // + XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization(); + // + // The PAP Engine + // + private static PAPPolicyEngine papEngine; + + public static String logTableLimit; + public static String systemAlertTableLimit; + 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; + + + //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; + //Xacml db properties + public static String xacmldbUrl = null; + public static String xacmldbUserName = null; + public static String xacmldbPassword = null; + + //AutoPush feature. + public static String autoPushAvailable; + public static String autoPushDSClosedLoop; + public static String autoPushDSFirewall; + public static String autoPushDSMicroservice; + public static String autoPushPDPGroup; + + //papURL + public static String papUrl; + + //MicroService Model Properties + public static String msEcompName; + public static String msPolicyName; + + @Autowired + private PolicyController(CommonClassDao commonClassDao){ + PolicyController.commonClassDao = commonClassDao; + } + + 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); + //pap url + papUrl = prop.getProperty("xacml.rest.pap.url"); + // 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"); + //Xacml Database Properties + xacmldbUrl = prop.getProperty("javax.persistence.jdbc.url"); + xacmldbUserName = prop.getProperty("javax.persistence.jdbc.user"); + xacmldbPassword = prop.getProperty("javax.persistence.jdbc.password"); + //AutoPuh + autoPushAvailable=prop.getProperty("xacml.automatic.push"); + autoPushDSClosedLoop=prop.getProperty("xacml.autopush.closedloop"); + autoPushDSFirewall=prop.getProperty("xacml.autopush.firewall"); + autoPushDSMicroservice=prop.getProperty("xacml.autopush.microservice"); + autoPushPDPGroup=prop.getProperty("xacml.autopush.pdpGroup"); + //Micro Service Properties + msEcompName=prop.getProperty("xacml.policy.msEcompName"); + msPolicyName=prop.getProperty("xacml.policy.msPolicyName"); + //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"; + } + 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 = commonClassDao.getData(FunctionDefinition.class); + for (int i = 0; i < functiondefinitions.size(); i ++) { + FunctionDefinition value = (FunctionDefinition) 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); + } + } + + @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(commonClassDao.getDataByColumn(FunctionDefinition.class, "shortname"))); + 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); + } + } + + public PolicyEntity getPolicyEntityData(String scope, String policyName){ + String key = scope + ":" + policyName; + List data = commonClassDao.getDataById(PolicyEntity.class, "scope:policyName", key); + PolicyEntity entity = (PolicyEntity) data.get(0); + return entity; + } + + public static Map getUserRoles(String userId) { + Map scopes = new HashMap(); + List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); + if (roles != null && roles.size() > 0) { + for (Object role : roles) { + scopes.put(((Roles) role).getScope(), (Roles) role); + } + } + return scopes; + } + + public static List getRolesOfUser(String userId) { + List rolesList = new ArrayList(); + List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); + for (Object role: roles) { + rolesList.add(((Roles) role).getRole()); + } + return rolesList; + } + + public static List getRoles(String userId) { + return commonClassDao.getDataById(Roles.class, "loginId", 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.getUserSession(request).getOrgUserId(); + 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/Editor" } , 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 PAPPolicyEngine getPapEngine() { + return papEngine; + } + + public void setPapEngine(PAPPolicyEngine papEngine) { + PolicyController.papEngine = papEngine; + } + + public String getUserName(String createdBy) { + String loginId = createdBy; + List data = commonClassDao.getDataById(UserInfo.class, "loginId", loginId); + return data.get(0).toString(); + } + + public static boolean getActivePolicy(String query) { + if(commonClassDao.getDataByQuery(query).size() > 0){ + return true; + }else{ + return false; + } + } + + public void executeQuery(String query) { + commonClassDao.updateQuery(query); + } + + public void saveData(Object cloneEntity) { + commonClassDao.save(cloneEntity); + } + + public void updateData(Object entity) { + commonClassDao.update(entity); + } + + public void deleteData(Object entity) { + commonClassDao.delete(entity); + } + + public PolicyVersion getPolicyEntityFromPolicyVersion(String query){ + PolicyVersion policyVersionEntity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); + return policyVersionEntity; + } + + public List getDataByQuery(String query){ + return commonClassDao.getDataByQuery(query); + } + + + @SuppressWarnings("rawtypes") + public Object getEntityItem(Class className, String columname, String key){ + return commonClassDao.getEntityItem(className, columname, key); + } + + + public void watchPolicyFunction(PolicyVersion entity, String policyName, String mode){ + PolicyNotificationMail email = new PolicyNotificationMail(); + try { + email.sendMail(entity, policyName, mode, commonClassDao); + } catch (MessagingException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Excepton Occured while Renaming/Deleting a Policy or Scope" + e); + } + } + + //Switch Version + public JSONObject switchVersionPolicyContent(String policyName) { + String dbCheckName = policyName.replace("/", "."); + if(dbCheckName.contains("Config_")){ + dbCheckName = dbCheckName.replace(".Config_", ":Config_"); + }else if(dbCheckName.contains("Action_")){ + dbCheckName = dbCheckName.replace(".Action_", ":Action_"); + }else if(dbCheckName.contains("Decision_")){ + dbCheckName = dbCheckName.replace(".Decision_", ":Decision_"); + } + String[] splitDBCheckName = dbCheckName.split(":"); + String query = "FROM PolicyEntity where policyName like'"+splitDBCheckName[1]+"%' and scope ='"+splitDBCheckName[0]+"'"; + List policyEntity = commonClassDao.getDataByQuery(query); + List av = new ArrayList(); + for(Object entity : policyEntity){ + PolicyEntity pEntity = (PolicyEntity) entity; + String removeExtension = pEntity.getPolicyName().replace(".xml", ""); + String version = removeExtension.substring(removeExtension.lastIndexOf(".")+1); + av.add(version); + } + if(policyName.contains("/")){ + policyName = policyName.replace("/", File.separator); + } + PolicyVersion entity = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", policyName); + JSONObject el = new JSONObject(); + el.put("activeVersion", entity.getActiveVersion()); + el.put("availableVersions", av); + el.put("highestVersion", entity.getHigherVersion()); + return el; + } +} + diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java new file mode 100644 index 000000000..b6899e041 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyExportAndImportController.java @@ -0,0 +1,367 @@ +/*- + * ============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.FileOutputStream; +import java.io.PrintWriter; +import java.util.ArrayList; +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.poi.hssf.usermodel.HSSFRow; +import org.apache.poi.hssf.usermodel.HSSFSheet; +import org.apache.poi.hssf.usermodel.HSSFWorkbook; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Row; +import org.apache.poi.ss.usermodel.Sheet; +import org.apache.poi.ss.usermodel.Workbook; +import org.json.JSONObject; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.adapter.PolicyExportAdapter; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.ActionBodyEntity; +import org.openecomp.policy.rest.jpa.ConfigurationDataEntity; +import org.openecomp.policy.rest.jpa.PolicyEditorScopes; +import org.openecomp.policy.rest.jpa.PolicyEntity; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.UserInfo; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +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 com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + + +@Controller +@RequestMapping("/") +public class PolicyExportAndImportController extends RestrictedBaseController { + private static Logger logger = FlexLogger.getLogger(PolicyExportAndImportController.class); + + private ArrayList selectedPolicy; + private Set scopes = null; + private List roles = null; + private static String SUPERADMIN = "super-admin"; + private static String SUPEREDITOR = "super-editor"; + private static String ADMIN = "admin"; + private static String EDITOR = "editor"; + + private static CommonClassDao commonClassDao; + + private PolicyEntity policyEntity; + private ConfigurationDataEntity configurationDataEntity; + private ActionBodyEntity actionBodyEntity; + private PolicyVersion policyVersion; + + private Workbook workbook; + + private HSSFWorkbook workBook2; + + @Autowired + private PolicyExportAndImportController(CommonClassDao commonClassDao){ + PolicyExportAndImportController.commonClassDao = commonClassDao; + } + + public PolicyExportAndImportController(){} + + @RequestMapping(value={"/policy_download/exportPolicy.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void ExportPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + try{ + String file = null; + 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; + String policyWithScope = selected.get("policyName").toString() + "." + selected.get("activeVersion").toString() + ".xml"; + String scope = policyWithScope.substring(0 , policyWithScope.lastIndexOf(File.separator)).replace(File.separator, "."); + String policyName = policyWithScope.substring(policyWithScope.lastIndexOf(File.separator)+1); + selectedPolicy.add(policyName+":"+scope); + } + List entityData = commonClassDao.getMultipleDataOnAddingConjunction(PolicyEntity.class, "policyName:scope", selectedPolicy); + + workBook2 = new HSSFWorkbook(); + HSSFSheet sheet = workBook2.createSheet("PolicyEntity"); + + HSSFRow headingRow = sheet.createRow(0); + headingRow.createCell(0).setCellValue("policyName"); + headingRow.createCell(1).setCellValue("scope"); + headingRow.createCell(2).setCellValue("version"); + headingRow.createCell(3).setCellValue("policyData"); + headingRow.createCell(4).setCellValue("description"); + headingRow.createCell(5).setCellValue("configurationbody"); + headingRow.createCell(6).setCellValue("configurationName"); + + short rowNo = 1; + for (Object object : entityData) { + PolicyEntity policyEntity = (PolicyEntity) object; + HSSFRow row = sheet.createRow(rowNo); + row.createCell(0).setCellValue(policyEntity.getPolicyName()); + row.createCell(1).setCellValue(policyEntity.getScope()); + row.createCell(2).setCellValue(policyEntity.getVersion()); + row.createCell(3).setCellValue(policyEntity.getPolicyData()); + row.createCell(4).setCellValue(policyEntity.getDescription()); + if(!policyEntity.getPolicyName().contains("Decision_")){ + if(policyEntity.getConfigurationData() != null){ + row.createCell(5).setCellValue(policyEntity.getConfigurationData().getConfigBody()); + row.createCell(6).setCellValue(policyEntity.getConfigurationData().getConfigurationName()); + } + if(policyEntity.getActionBodyEntity() != null){ + row.createCell(5).setCellValue(policyEntity.getActionBodyEntity().getActionBody()); + row.createCell(6).setCellValue(policyEntity.getActionBodyEntity().getActionBodyName()); + } + }else{ + row.createCell(5).setCellValue(""); + row.createCell(6).setCellValue(""); + } + rowNo++; + } + + String tmp = System.getProperty("catalina.base") + File.separator + "webapps" + File.separator + "temp"; + String deleteCheckPath = tmp + File.separator + "PolicyExport.xls"; + File deleteCheck = new File(deleteCheckPath); + if(deleteCheck.exists()){ + deleteCheck.delete(); + } + File temPath = new File(tmp); + if(!temPath.exists()){ + temPath.mkdir(); + } + + file = temPath + File.separator + "PolicyExport.xls"; + File filepath = new File(file); + FileOutputStream fos = new FileOutputStream(filepath); + workBook2.write(fos); + fos.flush(); + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String successMap = file.toString().substring(file.toString().lastIndexOf("webapps")+8); + String responseString = mapper.writeValueAsString(successMap); + JSONObject j = new JSONObject("{data: " + responseString + "}"); + out.write(j.toString()); + }catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while Exporting Policies"+e); + } + } + + //Policy Import + public JSONObject importRepositoryFile(String file, HttpServletRequest request) throws Exception{ + boolean configExists = false; + boolean actionExists = false; + String configName = null; + String scope = null; + boolean finalColumn = false; + PolicyController controller = new PolicyController(); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + UserInfo userInfo = (UserInfo) commonClassDao.getEntityItem(UserInfo.class, "userLoginId", 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(Object role: userRoles){ + Roles userRole = (Roles) role; + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + FileInputStream excelFile = new FileInputStream(new File(file)); + workbook = new HSSFWorkbook(excelFile); + Sheet datatypeSheet = workbook.getSheetAt(0); + Iterator rowIterator = datatypeSheet.iterator(); + + while (rowIterator.hasNext()) { + policyEntity = new PolicyEntity(); + configurationDataEntity = new ConfigurationDataEntity(); + actionBodyEntity = new ActionBodyEntity(); + policyVersion = new PolicyVersion(); + Row currentRow = rowIterator.next(); + if (currentRow.getRowNum() == 0) { + continue; + } + Iterator cellIterator = currentRow.cellIterator(); + while (cellIterator.hasNext()) { + Cell cell = cellIterator.next(); + if (getCellHeaderName(cell).equalsIgnoreCase("policyName")) { + policyEntity.setPolicyName(cell.getStringCellValue()); + } + if (getCellHeaderName(cell).equalsIgnoreCase("scope")) { + policyEntity.setScope(cell.getStringCellValue()); + } + if (getCellHeaderName(cell).equalsIgnoreCase("policyData")) { + policyEntity.setPolicyData(cell.getStringCellValue()); + } + if (getCellHeaderName(cell).equalsIgnoreCase("description")) { + policyEntity.setDescription(cell.getStringCellValue()); + } + if (getCellHeaderName(cell).equalsIgnoreCase("configurationbody")) { + if(policyEntity.getPolicyName().contains("Config_")){ + configExists = true; + configurationDataEntity.setConfigBody(cell.getStringCellValue()); + }else if(policyEntity.getPolicyName().contains("Action_")){ + actionExists = true; + actionBodyEntity.setActionBody(cell.getStringCellValue()); + } + } + if (getCellHeaderName(cell).equalsIgnoreCase("configurationName")) { + finalColumn = true; + configName = cell.getStringCellValue(); + if(policyEntity.getPolicyName().contains("Config_")){ + configurationDataEntity.setConfigurationName(cell.getStringCellValue()); + }else if(policyEntity.getPolicyName().contains("Action_")){ + actionBodyEntity.setActionBodyName(cell.getStringCellValue()); + } + } + + if(finalColumn){ + scope = policyEntity.getScope().replace(".", File.separator); + String query = "FROM PolicyEntity where policyName = '"+policyEntity.getPolicyName()+"' and scope ='"+policyEntity.getScope()+"'"; + List queryData = controller.getDataByQuery(query); + if(!queryData.isEmpty()){ + continue; + } + if (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR)) { + //1. if Role contains super admin create scope. + //2. if Role contains super editor don't create new scope and add to list to show to user. + + PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scope); + if(policyEditorScope == null){ + if(roles.contains(SUPERADMIN)){ + PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes(); + policyEditorScopeEntity.setScopeName(scope); + policyEditorScopeEntity.setUserCreatedBy(userInfo); + policyEditorScopeEntity.setUserModifiedBy(userInfo); + commonClassDao.save(policyEditorScopeEntity); + }else{ + //Add Error Message a new Scope Exists, contact super-admin to create a new scope + continue; + } + } + } + if (roles.contains(ADMIN) || roles.contains(EDITOR)) { + if(scopes.isEmpty()){ + //return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + }else{ + //1. if Role contains admin, then check if parent scope has role admin, if not don't create a scope and add to list. + if(roles.contains(ADMIN)){ + String scopeCheck = scope.substring(0, scope.lastIndexOf(".")); + if(scopes.contains(scopeCheck)){ + PolicyEditorScopes policyEditorScopeEntity = new PolicyEditorScopes(); + policyEditorScopeEntity.setScopeName(scope); + policyEditorScopeEntity.setUserCreatedBy(userInfo); + policyEditorScopeEntity.setUserModifiedBy(userInfo); + commonClassDao.save(policyEditorScopeEntity); + }else{ + continue; + } + }else{ + continue; + } + } + } + + if(configExists){ + if(configName.endsWith("json")){ + configurationDataEntity.setConfigType("JSON"); + }else if(configName.endsWith("txt")){ + configurationDataEntity.setConfigType("OTHER"); + }else if(configName.endsWith("xml")){ + configurationDataEntity.setConfigType("XML"); + }else if(configName.endsWith("properties")){ + configurationDataEntity.setConfigType("PROPERTIES"); + } + configurationDataEntity.setDeleted(false); + configurationDataEntity.setCreatedBy(userId); + configurationDataEntity.setModifiedBy(userId); + commonClassDao.save(configurationDataEntity); + } + if(actionExists){ + actionBodyEntity.setDeleted(false); + actionBodyEntity.setCreatedBy(userId); + actionBodyEntity.setModifiedBy(userId); + commonClassDao.save(actionBodyEntity); + } + if(configName != null){ + if(configName.contains("Config_")){ + ConfigurationDataEntity configuration = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", configName); + policyEntity.setConfigurationData(configuration); + }else{ + ActionBodyEntity actionBody = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", configName); + policyEntity.setActionBodyEntity(actionBody); + } + } + policyEntity.setCreatedBy(userId); + policyEntity.setModifiedBy(userId); + policyEntity.setDeleted(false); + commonClassDao.save(policyEntity); + + policyVersion = new PolicyVersion(); + String policyName = policyEntity.getPolicyName().replace(".xml", ""); + int version = Integer.parseInt(policyName.substring(policyName.lastIndexOf(".")+1)); + policyName = policyName.substring(0, policyName.lastIndexOf(".")); + + policyVersion.setPolicyName(scope.replace(".", File.separator) + File.separator + policyName); + policyVersion.setActiveVersion(version); + policyVersion.setHigherVersion(version); + policyVersion.setCreatedBy(userId); + policyVersion.setModifiedBy(userId); + commonClassDao.save(policyVersion); + } + } + } + return null; + } + + //return the column header name value + private String getCellHeaderName(Cell cell){ + String cellHeaderName = cell.getSheet().getRow(0).getCell(cell.getColumnIndex()).getRichStringCellValue().toString(); + return cellHeaderName; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyNotificationController.java new file mode 100644 index 000000000..768158453 --- /dev/null +++ b/POLICY-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.rest.dao.CommonClassDao; +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 + CommonClassDao commonClassDao; + + @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.getUserSession(request).getOrgUserId(); + 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 = commonClassDao.getDataByQuery(query); + if(watchList.isEmpty()){ + if(finalName.contains("\\\\")){ + finalName = finalName.replace("\\\\", File.separator); + } + WatchPolicyNotificationTable watch = new WatchPolicyNotificationTable(); + watch.setPolicyName(finalName); + watch.setLoginIds(userId); + commonClassDao.save(watch); + responseValue = "You have Subscribed Successfully"; + }else{ + commonClassDao.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/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java new file mode 100644 index 000000000..82090773c --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyRolesController.java @@ -0,0 +1,163 @@ +/*- + * ============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.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.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.PolicyEditorScopes; +import org.openecomp.policy.rest.jpa.PolicyRoles; +import org.openecomp.policy.rest.jpa.UserInfo; +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 + CommonClassDao commonClassDao; + + 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(commonClassDao.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{ + String scopeName = null; + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + ReadScopes adapter = mapper.readValue(root.get("editRoleData").toString(), ReadScopes.class); + for(int i = 0; i < adapter.getScope().size(); i++){ + if(i == 0){ + scopeName = adapter.getScope().get(0); + }else{ + scopeName = scopeName + "," + adapter.getScope().get(i); + } + } + PolicyRoles roles = new PolicyRoles(); + roles.setId(adapter.getId()); + roles.setLoginId(adapter.getLoginId()); + roles.setRole(adapter.getRole()); + roles.setScope(scopeName); + commonClassDao.update(roles); + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(commonClassDao.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); + List scopesData = commonClassDao.getDataByColumn(PolicyEditorScopes.class, "scopeName"); + model.put("scopeDatas", mapper.writeValueAsString(scopesData)); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + e.printStackTrace(); + } + } +} + +class ReadScopes{ + private int id; + private UserInfo loginId; + private String role; + private ArrayList scope; + + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + public UserInfo getLoginId() { + return loginId; + } + public void setLoginId(UserInfo loginId) { + this.loginId = loginId; + } + public String getRole() { + return role; + } + public void setRole(String role) { + this.role = role; + } + public ArrayList getScope() { + return scope; + } + public void setScope(ArrayList scope) { + this.scope = scope; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java new file mode 100644 index 000000000..55bff24a0 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/controller/PolicyValidationController.java @@ -0,0 +1,661 @@ +/*- + * ============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.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.PrintWriter; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Scanner; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import javax.json.Json; +import javax.json.JsonReader; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.parsers.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.apache.commons.lang.StringUtils; +import org.dom4j.util.XMLErrorHandler; +import org.json.JSONObject; +import org.openecomp.policy.rest.adapter.ClosedLoopFaultBody; +import org.openecomp.policy.rest.adapter.ClosedLoopPMBody; +import org.openecomp.policy.rest.adapter.PolicyRestAdapter; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.MicroServiceModels; +import org.openecomp.policy.rest.jpa.SafePolicyWarning; +import org.openecomp.policy.utils.PolicyUtils; +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 org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.CharMatcher; +import com.google.common.base.Splitter; +import com.google.common.base.Strings; + +@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="Micro Service"; + private Pattern pattern; + private Matcher matcher; + + private static Map rangeMap = new HashMap(); + private static Map mapAttribute = new HashMap(); + + 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 + CommonClassDao commonClassDao; + + @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()); + PolicyRestAdapter policyData = (PolicyRestAdapter)mapper.readValue(root.get("policyData").toString(), PolicyRestAdapter.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" + "
    "; + valid = false; + } + 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" + "
    "; + valid = false; + } + } + + if(policyData.getRiskType() != null){ + String riskTypeValidate = emptyValidator(policyData.getRiskType()); + if(!riskTypeValidate.contains("success")){ + responseString = responseString + "RiskType:" + riskTypeValidate + "
    "; + valid = false; + } + }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" + "
    "; + valid = false; + } + 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" + "
    "; + valid = false; + } + if(policyData.getConfigBodyData() != null){ + String configBodyData = policyData.getConfigBodyData(); + String policyType = policyData.getConfigType(); + if (policyType != null) { + if (policyType.equals("JSON")) { + if (!isJSONValid(configBodyData)) { + responseString = responseString + "Config Body: JSON Content is not valid" + "
    "; + valid = false; + } + } else if (policyType.equals("XML")) { + if (!isXMLValid(configBodyData)) { + responseString = responseString + "Config Body: XML Content data is not valid" + "
    "; + valid = false; + } + } else if (policyType.equals("PROPERTIES")) { + if (!isPropValid(configBodyData)||configBodyData.equals("")) { + responseString = responseString + "Config Body: Property data is not valid" + "
    "; + valid = false; + } + } else if (policyType.equals("OTHER")) { + if (configBodyData.equals("")) { + responseString = responseString + "Config Body: Config Body Should not be Empty" + "
    "; + valid = false; + } + } + } + }else{ + responseString = responseString + "Config Body: Config Body Should not be Empty" + "
    "; + valid = false; + } + } + + if(policyData.getConfigPolicyType().equals("Firewall Config")){ + if(policyData.getConfigName() != null){ + String configNameValidate = PolicyUtils.emptyPolicyValidator(policyData.getConfigName()); + if(!configNameValidate.contains("success")){ + responseString = responseString + "ConfigName:" + configNameValidate + "
    "; + valid = false; + } + }else{ + responseString = responseString + "Config Name: Config Name is required" + "
    "; + valid = false; + } + if(policyData.getSecurityZone() == null){ + responseString = responseString + "Security Zone: Security Zone is required" + "
    "; + valid = false; + } + } + if(policyData.getConfigPolicyType().equals("BRMS_Param")){ + if(policyData.getRuleName() == null){ + responseString = responseString + "BRMS Template:BRMS Template is required
    "; + valid = false; + } + } + if(policyData.getConfigPolicyType().equals("BRMS_Raw")){ + if(policyData.getConfigBodyData() != null){ + String message = PolicyUtils.brmsRawValidate(policyData.getConfigBodyData()); + // If there are any error other than Annotations then this is not Valid + if(message.contains("[ERR")){ + responseString = responseString + "Raw Rule Validate:Raw Rule has error"+ message +"
    "; + valid = false; + } + }else{ + responseString = responseString + "Raw Rule:Raw Rule is required
    "; + valid = false; + } + } + if(policyData.getConfigPolicyType().equals("ClosedLoop_PM")){ + try{ + if(root.get("policyData").get("verticaMetrics").get("serviceTypePolicyName") == null && policyData.getServiceTypePolicyName().isEmpty()){ + responseString = responseString + "ServiceType PolicyName:ServiceType PolicyName is required
    "; + valid = false; + } + }catch(Exception e){ + responseString = responseString + "ServiceType PolicyName:ServiceType PolicyName is required
    "; + valid = false; + } + + if(root.get("policyData").get("jsonBodyData") != null){ + ClosedLoopPMBody pmBody = (ClosedLoopPMBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopPMBody.class); + if(pmBody.getEmailAddress() != null){ + String result = emailValidation(pmBody.getEmailAddress(), responseString); + if(result != "success"){ + responseString = result + "
    "; + valid = false; + } + } + if(pmBody.getGeoLink() != null){ + String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink()); + if(!result.contains("success")){ + responseString = responseString + "GeoLink:" + result + "
    "; + valid = false; + }; + } + if(pmBody.getAttributes() != null){ + for(Entry entry : pmBody.getAttributes().entrySet()){ + String key = entry.getKey(); + String value = entry.getValue(); + if(!key.contains("Message")){ + String attributeValidate = PolicyUtils.emptyPolicyValidator(value); + if(!attributeValidate.contains("success")){ + responseString = responseString + "Attributes:" + key + " : value has spaces
    "; + valid = false; + }; + } + } + } + }else{ + responseString = responseString + "D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "; + valid = false; + } + } + if(policyData.getConfigPolicyType().equals("ClosedLoop_Fault")){ + if(root.get("policyData").get("jsonBodyData") != null){ + ClosedLoopFaultBody faultBody = (ClosedLoopFaultBody)mapper.readValue(root.get("policyData").get("jsonBodyData").toString(), ClosedLoopFaultBody.class); + if(faultBody.getEmailAddress() != null){ + String result = emailValidation(faultBody.getEmailAddress(), responseString); + if(result != "success"){ + responseString = result+ "
    "; + valid = false; + } + } + if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){ + responseString = responseString + "D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "; + valid = false; + } + if(faultBody.getActions() == null){ + responseString = responseString + "vPRO Actions:vPRO Actions is required
    "; + valid = false; + } + if(faultBody.getAgingWindow() == 0){ + responseString = responseString + "Aging Window:Aging Window is required
    "; + valid = false; + } + if(faultBody.getClosedLoopPolicyStatus() == null){ + responseString = responseString + "Policy Status:Policy Status is required
    "; + valid = false; + } + if(faultBody.getConditions() == null){ + responseString = responseString + "Conditions:Select Atleast one Condition
    "; + valid = false; + } + if(faultBody.getGeoLink() != null){ + String result = PolicyUtils.emptyPolicyValidator(faultBody.getGeoLink()); + if(!result.contains("success")){ + responseString = responseString + "GeoLink:" + result + "
    "; + valid = false; + }; + } + + if(faultBody.getTimeInterval() == 0){ + responseString = responseString + "Time Interval:Time Interval is required
    "; + valid = false; + } + if(faultBody.getRetrys() == 0){ + responseString = responseString + "Number of Retries:Number of Retries is required
    "; + valid = false; + } + if(faultBody.getTimeOutvPRO() == 0){ + responseString = responseString + "APP-C Timeout:APP-C Timeout is required
    "; + valid = false; + } + if(faultBody.getTimeOutRuby() == 0){ + responseString = responseString + "TimeOutRuby:TimeOutRuby is required
    "; + valid = false; + } + if(faultBody.getVnfType() == null){ + responseString = responseString + "Vnf Type:Vnf Type is required
    "; + valid = false; + } + }else{ + responseString = responseString + "D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "; + responseString = responseString + "vPRO Actions:vPRO Actions is required
    "; + responseString = responseString + "Aging Window:Aging Window is required
    "; + responseString = responseString + "Policy Status:Policy Status is required
    "; + responseString = responseString + "Conditions:Select Atleast one Condition
    "; + responseString = responseString + "PEP Name:PEP Name is required
    "; + responseString = responseString + "PEP Action:PEP Action is required
    "; + responseString = responseString + "Time Interval:Time Interval is required
    "; + responseString = responseString + "Number of Retries:Number of Retries is required
    "; + responseString = responseString + "APP-C Timeout:APP-C Timeout is required
    "; + responseString = responseString + "TimeOutRuby:TimeOutRuby is required
    "; + responseString = responseString + "Vnf Type:Vnf Type is required
    "; + valid = false; + } + } + + if (policyData.getConfigPolicyType().contains("Micro Service")){ + if(policyData.getServiceType() != null){ + pullJsonKeyPairs(root.get("policyJSON")); + MicroServiceModels returnModel = new MicroServiceModels(); + String service = null; + String version = null; + if (policyData.getServiceType().contains("-v")){ + service = policyData.getServiceType().split("-v")[0]; + version = policyData.getServiceType().split("-v")[1]; + }else { + service = policyData.getServiceType(); + version = policyData.getVersion(); + } + returnModel = getAttributeObject(service, version); + String annoation = returnModel.getAnnotation(); + if (!Strings.isNullOrEmpty(annoation)){ + rangeMap = new HashMap(); + rangeMap = Splitter.on(",").withKeyValueSeparator("=").split(annoation); + for (Entry rMap : rangeMap.entrySet()){ + if (rMap.getValue().contains("range::")){ + String value = mapAttribute.get(rMap.getKey().trim()); + String[] tempString = rMap.getValue().split("::")[1].split("-"); + int startNum = Integer.parseInt(tempString[0]); + int endNum = Integer.parseInt(tempString[1]); + String returnString = "Invalid Range:" + rMap.getKey() + " must be between " + + startNum + " - " + endNum + ","; + if (isType(value.replace("\"", ""))){ + int result = Integer.parseInt(value.replace("\"", "")); + + + if (result < startNum || result > endNum){ + responseString = responseString + returnString; + valid = false; + } + }else { + responseString = responseString + returnString; + valid = false; + } + } + } + } + //for continue testing for Dkat, just blocked this validation until fixing it. gw1218 on 3/30/17 + //if (!checkAttributeValues()){ + //responseString = responseString + "Micro Service: Attribute Values Missing" + "
    "; + //valid = false; + //} + + }else{ + responseString = responseString + "Micro Service: Micro Service is required" + "
    "; + valid = false; + } + + if(policyData.getPriority() == null){ + responseString = responseString + "Priority: Priority is required" + "
    "; + valid = false; + } + } + } + if (policyData.getPolicyType().equals(DECISION_POLICY)){ + 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" + "
    "; + valid = false; + } + + } + + if(policyData.getPolicyType().equals(ACTION_POLICY)){ + if(policyData.getActionPerformer() != null){ + String actionPerformer = emptyValidator(policyData.getActionPerformer()); + if(!actionPerformer.contains("success")){ + responseString = responseString + "ActionPerformer:" + actionPerformer + "
    "; + valid = false; + }; + }else{ + responseString = responseString + "ActionPerformer: ActionPerformer Should not be empty" + "
    "; + valid = false; + } + if(policyData.getActionAttributeValue() != null){ + String actionAttribute = emptyValidator(policyData.getActionAttributeValue()); + if(!actionAttribute.contains("success")){ + responseString = responseString + "ActionAttribute:" + actionAttribute + "
    "; + valid = false; + }; + }else{ + responseString = responseString + "ActionAttribute: ActionAttribute Should not be empty" + "
    "; + valid = false; + } + } + + if(policyData.getPolicyType().equals(CONFIG_POLICY)){ + if(valid){ + List spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType()); + if (!spData.isEmpty()){ + SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0); + safePolicyWarningData.getMessage(); + responseString = responseString + "Messaage:" + safePolicyWarningData.getMessage(); + } + 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; + } + + protected String emailValidation(String email, String responseString){ + if(email != null){ + String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", "")); + if(!validateEmail.contains("success")){ + responseString = responseString + "Email:" + validateEmail+ "
    "; + }else{ + return "success"; + } + } + return responseString; + } + + private MicroServiceModels getAttributeObject(String name, String version) { + MicroServiceModels workingModel = new MicroServiceModels(); + List microServiceModelsData = commonClassDao.getDataById(MicroServiceModels.class, "modelName:version", name+":"+version); + if(microServiceModelsData != null){ + workingModel = (MicroServiceModels) microServiceModelsData.get(0); + } + return workingModel; + } + + private void pullJsonKeyPairs(JsonNode rootNode) { + Iterator> fieldsIterator = rootNode.fields(); + + while (fieldsIterator.hasNext()) { + Map.Entry field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullJsonKeyPairs(value); // RECURSIVE CALL + } else { + if (value.isArray()){ + String newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); + mapAttribute.put(key, newValue); + }else { + mapAttribute.put(key, value.toString().trim()); + } + } + } + } + + private Boolean isType(String testStr) { + try { + Integer.parseInt(testStr); + return true; + } catch(Exception e) { + return false; + } + } + + // Validation for json. + protected static boolean isJSONValid(String data) { + try { + new JSONObject(data); + InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + JsonReader jsonReader = Json.createReader(stream); + System.out.println("Json Value is: " + jsonReader.read().toString() ); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + return true; + } + + // Validation for XML. + private boolean isXMLValid(String data) { + SAXParserFactory factory = SAXParserFactory.newInstance(); + factory.setValidating(false); + factory.setNamespaceAware(true); + try { + SAXParser parser = factory.newSAXParser(); + XMLReader reader = parser.getXMLReader(); + reader.setErrorHandler(new XMLErrorHandler()); + reader.parse(new InputSource(new StringReader(data))); + } catch (ParserConfigurationException e) { + return false; + } catch (SAXException e) { + return false; + } catch (IOException e) { + return false; + } + return true; + } + + // Validation for Properties file. + public boolean isPropValid(String prop) { + Scanner scanner = new Scanner(prop); + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + line.replaceAll("\\s+", ""); + if (line.startsWith("#")) { + continue; + } else { + if (line.contains("=")) { + String[] parts = line.split("="); + if (parts.length < 2) { + scanner.close(); + return false; + } + } else { + scanner.close(); + return false; + } + } + } + scanner.close(); + return true; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java new file mode 100644 index 000000000..bdfdd8f0a --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/dao/SystemLogDbDao.java @@ -0,0 +1,33 @@ +/*- + * ============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.dao; + + +import java.util.List; + +import org.openecomp.policy.rest.jpa.SystemLogDB; + + + +public abstract interface SystemLogDbDao { + public abstract List getLoggingData(); + public abstract List getSystemAlertData(); +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java new file mode 100644 index 000000000..6ac4afbcf --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/CommonClassDaoImpl.java @@ -0,0 +1,385 @@ +/*- + * ============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.daoImp; + +import java.util.ArrayList; +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Query; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; +import org.hibernate.criterion.Conjunction; +import org.hibernate.criterion.Disjunction; +import org.hibernate.criterion.Projections; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.rest.dao.CommonClassDao; +import org.openecomp.policy.rest.jpa.PolicyRoles; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +@Service("CommonClassDao") +public class CommonClassDaoImpl implements CommonClassDao{ + + private static final Logger LOGGER = FlexLogger.getLogger(CommonClassDaoImpl.class); + + @Autowired + SessionFactory sessionfactory; + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public List getData(Class className) { + Session session = sessionfactory.openSession(); + List data = null; + try{ + Criteria cr = session.createCriteria(className); + data = cr.list(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } + } + return data; + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public List getDataById(Class className, String columnName, String key) { + Session session = sessionfactory.openSession(); + List data = null; + try { + Criteria cr = session.createCriteria(className); + if(columnName.contains(":") && key.contains(":")){ + String[] columns = columnName.split(":"); + String[] keys = key.split(":"); + for(int i=0; i < columns.length; i++){ + cr.add(Restrictions.eq(columns[i], keys[i])); + } + }else{ + cr.add(Restrictions.eq(columnName, key)); + } + data = cr.list(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + @Override + public void save(Object entity) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.persist(entity); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + @Override + public void delete(Object entity) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.delete(entity); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @Override + public void update(Object entity) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + session.update(entity); + tx.commit(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @Override + public List checkDuplicateEntry(String value, String columnName, Class className) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List data = null; + String[] columnNames = null; + if(columnName != null && columnName.contains(":")){ + columnNames = columnName.split(":"); + } + String[] values = null; + if(value != null && value.contains(":")){ + values = value.split(":"); + } + try { + Criteria cr = session.createCriteria(className); + if(columnNames != null && values != null && columnNames.length == values.length){ + for (int i = 0; i < columnNames.length; i++){ + cr.add(Restrictions.eq(columnNames[i],values[i])); + } + }else{ + cr.add(Restrictions.eq(columnName,value)); + } + data = cr.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table"+e + className); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + + @SuppressWarnings("unchecked") + @Override + public List getUserRoles() { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List rolesData = null; + try { + Criteria cr = session.createCriteria(PolicyRoles.class); + Disjunction disjunction = Restrictions.disjunction(); + Conjunction conjunction1 = Restrictions.conjunction(); + conjunction1.add(Restrictions.eq("role", "admin")); + Conjunction conjunction2 = Restrictions.conjunction(); + conjunction2.add(Restrictions.eq("role", "editor")); + Conjunction conjunction3 = Restrictions.conjunction(); + conjunction3.add(Restrictions.eq("role", "guest")); + disjunction.add(conjunction1); + disjunction.add(conjunction2); + disjunction.add(conjunction3); + rolesData = cr.add(disjunction).list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return rolesData; + } + + + @Override + public List checkExistingGroupListforUpdate(String arg0, String arg1) { + return null; + } + + + @Override + public void deleteAll() {} + + + @SuppressWarnings("unchecked") + @Override + public List getDataByQuery(String query) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List data = null; + try { + Query hbquery = session.createQuery(query); + data = hbquery.list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + + @SuppressWarnings("rawtypes") + @Override + public Object getEntityItem(Class className, String columnName, String key) { + System.out.println(columnName); + System.out.println(key); + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + Object data = null; + try { + Criteria cr = session.createCriteria(className); + if(columnName.contains(":") && key.contains(":")){ + String[] columns = columnName.split(":"); + String[] keys = key.split(":"); + for(int i=0; i < columns.length; i++){ + cr.add(Restrictions.eq(columns[i], keys[i])); + } + }else{ + cr.add(Restrictions.eq(columnName, key)); + } + data = cr.list().get(0); + System.out.println(data); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return data; + } + + + @Override + public void updateClAlarms(String arg0, String arg1) {} + + + @Override + public void updateClYaml(String arg0, String arg1) {} + + + @Override + public void updateQuery(String query) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + try { + Query hbquery = session.createQuery(query); + hbquery.executeUpdate(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public List getDataByColumn(Class className, String columnName) { + Session session = sessionfactory.openSession(); + List data = null; + try{ + Criteria cr = session.createCriteria(className); + cr.setProjection(Projections.property(columnName)); + data = cr.list(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e); + } + } + return data; + } + + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @Override + public List getMultipleDataOnAddingConjunction(Class className, String columnName, List data) { + Session session = sessionfactory.openSession(); + Transaction tx = session.beginTransaction(); + List entityData = null; + try { + Criteria cr = session.createCriteria(className); + Disjunction disjunction = Restrictions.disjunction(); + List conjunctionList = new ArrayList(); + String[] columNames = columnName.split(":"); + for(int i =0; i < data.size(); i++){ + String[] entiySplit = data.get(i).split(":"); + Conjunction conjunction = Restrictions.conjunction(); + conjunction.add(Restrictions.eq(columNames[0], entiySplit[0])); + conjunction.add(Restrictions.eq(columNames[1], entiySplit[1])); + conjunctionList.add(conjunction); + } + for(int j =0 ; j < conjunctionList.size(); j++){ + disjunction.add(conjunctionList.get(j)); + } + entityData = cr.add(disjunction).list(); + tx.commit(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Table" +className +e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return entityData; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java new file mode 100644 index 000000000..927d20f2f --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/daoImp/SystemLogDbDaoImpl.java @@ -0,0 +1,93 @@ +/*- + * ============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.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.springframework.stereotype.Service; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.openecomp.policy.conf.HibernateSession; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.dao.SystemLogDbDao; +import org.openecomp.policy.rest.jpa.SystemLogDB; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +@Service("SystemLogDbDao") +public class SystemLogDbDaoImpl implements SystemLogDbDao { + private static final Logger logger = FlexLogger.getLogger(SystemLogDbDaoImpl.class); + @SuppressWarnings("unchecked") + @Override + public List getLoggingData() { + Session session = HibernateSession.getSession(); + Transaction tx = session.beginTransaction(); + List system = null; + try { + String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) ORDER BY date DESC limit "+PolicyController.logTableLimit+""; + Criteria cr = session.createCriteria(SystemLogDB.class); + cr.add(Restrictions.sqlRestriction(sqlWhere)); + system = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return system; + } + + @SuppressWarnings("unchecked") + @Override + public List getSystemAlertData() { + Session session = HibernateSession.getSession();; + Transaction tx = session.beginTransaction(); + List system = null; + try { + String sqlWhere = "date > DATE_SUB(curdate(), INTERVAL 5 DAY) and logtype = 'error' ORDER BY date DESC limit "+PolicyController.systemAlertTableLimit+""; + Criteria cr = session.createCriteria(SystemLogDB.class); + cr.add(Restrictions.sqlRestriction(sqlWhere)); + system = cr.list(); + tx.commit(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying SystemLogDB Table"+e); + }finally{ + try{ + session.close(); + }catch(Exception e1){ + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement"+e1); + } + } + return system; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java new file mode 100644 index 000000000..9d001b3ab --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPGroupContainer.java @@ -0,0 +1,528 @@ +/*- + * ============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.model; + + +import java.awt.Checkbox; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; +import org.openecomp.policy.utils.PolicyContainer; +import org.openecomp.policy.utils.PolicyItemSetChangeNotifier; +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDP; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; +import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; + +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDP; +//import com.att.research.xacml.api.pap.PDP; +//import com.att.research.xacml.api.pap.PDPGroup; +import com.att.research.xacml.api.pap.PDPPIPConfig; +import com.att.research.xacml.api.pap.PDPPolicy; + +public class PDPGroupContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed, PolicyContainer.ItemSetChangeNotifier { + private static final long serialVersionUID = 1L; + private static Logger LOGGER = FlexLogger.getLogger(PDPGroupContainer.class); + + /** + * String identifier of a file's "Id" property. + */ + public static String PROPERTY_ID = "Id"; + + /** + * String identifier of a file's "name" property. + */ + public static String PROPERTY_NAME = "Name"; + + /** + * String identifier of a file's "Description" property. + */ + public static String PROPERTY_DESCRIPTION = "Description"; + + /** + * String identifier of a file's "Default" property. + */ + public static String PROPERTY_DEFAULT = "Default"; + + /** + * String identifier of a file's "icon" property. + */ + public static String PROPERTY_ICON = "Icon"; + + /** + * String identifier of a file's "Status" property. + */ + public static String PROPERTY_STATUS = "Status"; + + /** + * String identifier of a file's "PDPs" property. + */ + public static String PROPERTY_PDPS = "PDPs"; + + /** + * String identifier of a file's "Policies" property. + */ + public static String PROPERTY_POLICIES = "Policies"; + + /** + * String identifier of a file's "PIP Configurations" property. + */ + public static String PROPERTY_PIPCONFIG = "PIP Configurations"; + + /** + * String identifier of a file's "Selected" property. + */ + public static String PROPERTY_SELECTED = "Selected"; + + /** + * List of the string identifiers for the available properties. + */ + public static Collection PDP_PROPERTIES; + + private PAPPolicyEngine papEngine = null; + protected List groups = Collections.synchronizedList(new ArrayList()); + + public PDPGroupContainer(PAPPolicyEngine papPolicyEngine) { + super(); + this.setContainer(this); + // + // + // + this.papEngine = (PAPPolicyEngine) papPolicyEngine; + // + // + // + this.refreshGroups(); + } + + public boolean isSupported(Object itemId) { + if (itemId instanceof EcompPDPGroup) { + return true; + } + return false; + } + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + this.groups.addAll(this.papEngine.getEcompPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + } + LOGGER.info("refreshGroups"); + } + // + // Notify that we have changed + // + this.fireItemSetChange(); + } + + public List getGroups() { + return Collections.unmodifiableList(this.groups); + } + + public void makeDefault(EcompPDPGroup group) { + try { + this.papEngine.SetDefaultGroup(group); + } catch (PAPException e) { + String message = "Unable to set Default Group on server: " + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + } + return; + } + + public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup) throws PAPException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("removeGroup: " + group + " new group for PDPs: " + newGroup); + } + if (group.isDefaultGroup()) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + } + try { + this.papEngine.removeGroup(group, newGroup); + } catch (NullPointerException | PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to removeGroup " + group.getId(), e); + throw new PAPException("Failed to remove group '" + group.getId()+ "'", e); + } + } + + public void removePDP(EcompPDP pdp, EcompPDPGroup group) throws PAPException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("removePDP: " + pdp + " from group: " + group); + } + try { + this.papEngine.removePDP(pdp); + } catch (PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to removePDP " + pdp.getId(), e); + throw new PAPException("Failed to remove pdp '" + pdp.getId()+ "'", e); + } + } + + public void updatePDP(EcompPDP pdp) { + try { + papEngine.updatePDP(pdp); + } catch (PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + public void updateGroup(EcompPDPGroup group) { + try { + papEngine.updateGroup(group); + } catch (PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + @Override + public Collection getContainerPropertyIds() { + return PDP_PROPERTIES; + } + + @Override + public Collection getItemIds() { + final Collection items = new ArrayList(); + items.addAll(this.groups); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getItemIds: " + items); + } + return Collections.unmodifiableCollection(items); + } + + @Override + public Class getType(Object propertyId) { + if (propertyId.equals(PROPERTY_ID)) { + return String.class; + } + if (propertyId.equals(PROPERTY_NAME)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DESCRIPTION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DEFAULT)) { + return Boolean.class; + } + if (propertyId.equals(PROPERTY_STATUS)) { + return String.class; + } + if (propertyId.equals(PROPERTY_PDPS)) { + return Set.class; + } + if (propertyId.equals(PROPERTY_POLICIES)) { + return Set.class; + } + if (propertyId.equals(PROPERTY_PIPCONFIG)) { + return Set.class; + } + if (propertyId.equals(PROPERTY_SELECTED)) { + return Checkbox.class; + } + return null; + } + + @Override + public int size() { + return this.groups.size(); + } + + @Override + public boolean containsId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("containsId: " + itemId); + } + if (this.isSupported(itemId) == false) { + return false; + } + return this.groups.contains(itemId); + } + + @Override + public Object addItem() throws UnsupportedOperationException { + throw new UnsupportedOperationException("PDP Container cannot add a given item."); + } + + public void addNewGroup(String name, String description) throws NullPointerException, PAPException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("addNewGroup " + name + " " + description); + } + this.papEngine.newGroup(name, description); + } + + public void addNewPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws NullPointerException, PAPException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("addNewPDP " + id + " " + name + " " + description + " " + jmxport); + } + this.papEngine.newPDP(id, group, name, description, jmxport); + } + + public void movePDP(EcompPDP pdp, EcompPDPGroup group) { + try { + this.papEngine.movePDP(pdp, group); + } catch (PAPException e) { + String message = "Unable to move PDP to new group on server: " + e; + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + } + return; + } + + @Override + public boolean addContainerProperty(Object propertyId, Class type, Object defaultValue) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot add a container property."); + } + + @Override + public boolean removeContainerProperty(Object propertyId) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot remove a container property."); + } + + @Override + public boolean removeAllItems() throws UnsupportedOperationException { + throw new UnsupportedOperationException("PDP Container cannot remove all items. You must have at least the Default group."); + } + + @Override + public void addItemSetChangeListener(ItemSetChangeListener listener) { + if (getItemSetChangeListeners() == null) { + setItemSetChangeListeners(new LinkedList()); + } + getItemSetChangeListeners().add(listener); + } + + @Override + public Object nextItemId(Object itemId) { + if (this.isSupported(itemId) == false) { + return null; + } + int index = this.groups.indexOf(itemId); + if (index == -1) { + // + // We don't know this group + // + return null; + } + // + // Is it the last one? + // + if (index == this.groups.size() - 1) { + // + // Yes + // + return null; + } + // + // Return the next one + // + return this.groups.get(index + 1); + } + + @Override + public Object prevItemId(Object itemId) { + if (this.isSupported(itemId) == false) { + return null; + } + int index = this.groups.indexOf(itemId); + if (index == -1) { + // + // We don't know this group + // + return null; + } + // + // Is it the first one? + // + if (index == 0) { + // + // Yes + // + return null; + } + // + // Return the previous one + // + return this.groups.get(index - 1); + } + + @Override + public Object firstItemId() { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return this.groups.get(0); + } + } + return null; + } + + @Override + public Object lastItemId() { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return this.groups.get(this.groups.size() - 1); + } + } + return null; + } + + @Override + public boolean isFirstId(Object itemId) { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return (this.groups.get(0).equals(itemId)); + } + } + return false; + } + + @Override + public boolean isLastId(Object itemId) { + synchronized (this.groups) { + if (this.groups.size() > 0) { + return (this.groups.get(this.groups.size() - 1).equals(itemId)); + } + } + return false; + } + + @Override + public Object addItemAfter(Object previousItemId) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot addItemAfter, there really is no real ordering."); + } + + @Override + public int indexOfId(Object itemId) { + return this.groups.indexOf(itemId); + } + + @Override + public Object getIdByIndex(int index) { + return this.groups.get(index); + } + + @Override + public List getItemIds(int startIndex, int numberOfItems) { + synchronized (this.groups) { + int endIndex = startIndex + numberOfItems; + if (endIndex > this.groups.size()) { + endIndex = this.groups.size() - 1; + } + return this.groups.subList(startIndex, endIndex); + } + } + + @Override + public Object addItemAt(int index) throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot addItemAt"); + } + + @Override + public boolean removeItem(Object itemId) throws UnsupportedOperationException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("removeItem: " + itemId); + } + if (this.isSupported(itemId) == false) { + return false; + } + // + // You cannot remove the default group + // + if (((EcompPDPGroup) itemId).getId().equals("Default")) { + throw new UnsupportedOperationException("You can't remove the Default Group."); + } + // + // Remove PDPGroup and move any PDP's in it into the default group + // + try { + this.papEngine.removeGroup((EcompPDPGroup) itemId, this.papEngine.getDefaultGroup()); + return true; + } catch (NullPointerException | PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to remove group", e); + } + return false; + } + + public class PDPGroupItem{ + private final EcompPDPGroup group; + + public PDPGroupItem(EcompPDPGroup itemId) { + this.group = itemId; + } + + public String getId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getId: " + this.group); + } + return this.group.getId(); + } + + public String getName() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getName: " + this.group); + } + return this.group.getName(); + } + + public String getDescription() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getDescription: " + this.group); + } + return this.group.getDescription(); + } + + public Boolean getDefault() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getDefault: " + this.group); + } + return this.group.isDefaultGroup(); + } + + + public String getStatus() { + return this.group.getStatus().getStatus().toString(); + } + + public Set getPDPs() { + return Collections.unmodifiableSet(this.group.getPdps()); + } + + public Set getPolicies() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getPolicies: " + this.group); + } + return this.group.getPolicies(); + } + + public Set getPipConfigs() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getPIPConfigs: " + this.group); + } + return this.group.getPipConfigs(); + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java new file mode 100644 index 000000000..353a903be --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/PDPPolicyContainer.java @@ -0,0 +1,348 @@ +/*- + * ============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.model; + + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.openecomp.policy.utils.PolicyContainer; +import org.openecomp.policy.utils.PolicyItemSetChangeNotifier; +import org.openecomp.policy.common.logging.flexlogger.*; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +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 org.openecomp.policy.xacml.std.pap.StdPDPPolicy; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PDPPolicyContainer extends PolicyItemSetChangeNotifier implements PolicyContainer.Indexed { + private static final long serialVersionUID = 1L; + private static Logger LOGGER = FlexLogger.getLogger(PDPPolicyContainer.class); + + /** + * String identifier of a file's "Id" property. + */ + public static String PROPERTY_ID = "Id"; + + /** + * String identifier of a file's "name" property. + */ + public static String PROPERTY_NAME = "Name"; + + /** + * String identifier of a file's "name" property. + */ + public static String PROPERTY_VERSION = "Version"; + + /** + * String identifier of a file's "Description" property. + */ + public static String PROPERTY_DESCRIPTION = "Description"; + + /** + * String identifier of a file's "IsRoot" property. + */ + public static String PROPERTY_ISROOT = "Root"; + + /** + * List of the string identifiers for the available properties. + */ + public static Collection PDPPOLICY_PROPERTIES; + + private final Object data; + private List policies; + + @SuppressWarnings("unchecked") + public PDPPolicyContainer(Object data) { + super(); + this.data = data; + if (this.data instanceof PDPGroup) { + policies = new ArrayList (((PDPGroup) this.data).getPolicies()); + } + if (this.data instanceof PDP) { + policies = new ArrayList (((PDP) this.data).getPolicies()); + } + if (this.data instanceof Set) { + policies = new ArrayList ((Set)data); + } + if (this.policies == null) { + LOGGER.info("NULL policies"); + throw new NullPointerException("PDPPolicyContainer created with unexpected Object type '" + data.getClass().getName() + "'"); + } + this.setContainer(this); + } + + @Override + public Object nextItemId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("nextItemId: " + itemId); + } + int index = this.policies.indexOf(itemId); + if (index == -1 || ((index + 1) >= this.policies.size())) { + return null; + } + return new PDPPolicyItem(this.policies.get(index + 1)); + } + + @Override + public Object prevItemId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("prevItemId: " + itemId); + } + int index = this.policies.indexOf(itemId); + if (index <= 0) { + return null; + } + return new PDPPolicyItem(this.policies.get(index - 1)); + } + + @Override + public Object firstItemId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("firstItemId: "); + } + if (this.policies.isEmpty()) { + return null; + } + return new PDPPolicyItem(this.policies.get(0)); + } + + @Override + public Object lastItemId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("lastItemid: "); + } + if (this.policies.isEmpty()) { + return null; + } + return new PDPPolicyItem(this.policies.get(this.policies.size() - 1)); + } + + @Override + public boolean isFirstId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("isFirstId: " + itemId); + } + if (this.policies.isEmpty()) { + return false; + } + return (itemId.equals(this.policies.get(0))); + } + + @Override + public boolean isLastId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("isLastId: " + itemId); + } + if (this.policies.isEmpty()) { + return false; + } + return (itemId.equals(this.policies.get(this.policies.size() - 1))); + } + + @Override + public Object addItemAfter(Object previousItemId) + throws UnsupportedOperationException { + return null; + } + + @Override + public Collection getContainerPropertyIds() { + return PDPPOLICY_PROPERTIES; + } + + @Override + public Collection getItemIds() { + final Collection items = new ArrayList(); + items.addAll(this.policies); + return Collections.unmodifiableCollection(items); + } + + + @Override + public Class getType(Object propertyId) { + if (propertyId.equals(PROPERTY_ID)) { + return String.class; + } + if (propertyId.equals(PROPERTY_NAME)) { + return String.class; + } + if (propertyId.equals(PROPERTY_VERSION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_DESCRIPTION)) { + return String.class; + } + if (propertyId.equals(PROPERTY_ISROOT)) { + return Boolean.class; + } + return null; + } + + @Override + public int size() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("size: " + this.policies.size()); + } + return this.policies.size(); + } + + @Override + public boolean containsId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("containsId: " + itemId); + } + return this.policies.contains(itemId); + } + + @Override + public Object addItem() throws UnsupportedOperationException { + throw new UnsupportedOperationException("Cannot add an empty policy."); + } + + @Override + public boolean removeItem(Object itemId) + throws UnsupportedOperationException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("removeItem: " + itemId); + } + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + StdPDPPolicy pdpPolicy = null; + try { + pdpPolicy = mapper.readValue(itemId.toString() , StdPDPPolicy.class); + for(int i = 0; i< policies.size(); i++){ + if(policies.get(i).getId().equalsIgnoreCase(pdpPolicy.getId())){ + return this.policies.remove(this.policies.get(i)); + } + } + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Mapping the Removing Policy from PDP Group to Std Policy"+e); + } + return this.policies.remove(itemId); + } + + @Override + public boolean addContainerProperty(Object propertyId, Class type, + Object defaultValue) throws UnsupportedOperationException { + return false; + } + + @Override + public boolean removeContainerProperty(Object propertyId) + throws UnsupportedOperationException { + return false; + } + + @Override + public boolean removeAllItems() throws UnsupportedOperationException { + return false; + } + + @Override + public int indexOfId(Object itemId) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("indexOfId: " + itemId); + } + return this.policies.indexOf(itemId); + } + + @Override + public Object getIdByIndex(int index) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getIdByIndex: " + index); + } + return this.policies.get(index); + } + + @Override + public List getItemIds(int startIndex, int numberOfItems) { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getItemIds: " + startIndex + " " + numberOfItems); + } + if (numberOfItems < 0) { + throw new IllegalArgumentException(); + } + return this.policies.subList(startIndex, startIndex + numberOfItems); + } + + @Override + public Object addItemAt(int index) throws UnsupportedOperationException { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("addItemAt: " + index); + } + return null; + } + + public class PDPPolicyItem { + private final PDPPolicy policy; + + public PDPPolicyItem(PDPPolicy itemId) { + this.policy = itemId; + } + + public String getId() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getId: " + this.policy); + } + return this.policy.getId(); + } + + public String getName() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getName: " + this.policy); + } + return this.policy.getName(); + } + + public String getVersion() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getVersion: " + this.policy); + } + return this.policy.getVersion(); + } + + public String getDescription() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("getDescription: " + this.policy); + } + return this.policy.getDescription(); + } + + public boolean getRoot() { + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("isRoot: " + this.policy); + } + return this.policy.isRoot(); + } + + public void setRoot(Boolean root) { + ((StdPDPPolicy)this.policy).setRoot(root); + } + + } +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/Roles.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/Roles.java new file mode 100644 index 000000000..9cb554a2a --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/model/Roles.java @@ -0,0 +1,99 @@ +/*- + * ============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.model; + + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.NamedQuery; +import javax.persistence.Table; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; + +@Entity +@Table(name="Roles") +@NamedQuery(name="Roles.findAll", query="SELECT r FROM Roles r ") +@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) +public class Roles implements Serializable{ + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + + @Column(name="id") + private int id; + + @Column(name="loginId") + private String loginId; + + private String name; + private String scope; + private String role; + + public Roles(){ + + } + + public int getId() { + return this.id; + } + + public void setId(int id) { + this.id = id; + } + + public String getLoginId() { + return this.loginId; + } + + public void setLoginId(String loginId) { + this.loginId = loginId; + + } + public String getScope() { + return this.scope; + } + + public void setScope(String scope) { + this.scope = scope; + + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + public String getRole() { + return this.role; + } + + public void setRole(String role) { + this.role = role; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java new file mode 100644 index 000000000..4ebc01c0c --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/ConfigurableRESTUtils.java @@ -0,0 +1,163 @@ +/*- + * ============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.utils; + + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.Map; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + + +public class ConfigurableRESTUtils { + + protected Logger LOGGER = FlexLogger.getLogger(this.getClass()); + + // + // How the value is returned from the RESTful server + // httpResponseCode means the result is simply the HTTP Response code (e.g. 200, 505, etc.) + // other values identify the encoding used for the string in the body of the HTTP response + // + public enum REST_RESPONSE_FORMAT {httpResponseCode, json } + public enum RESQUEST_METHOD { + GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE; + } + + public String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: "; + + public ConfigurableRESTUtils() { + + } + + + /** + * Call the RESTful API and return a string containing the result. The string may be either a httpResponseCode or json body + * + * @param fullURI + * @param hardCodedHeaders + * @param httpResponseCodes + * @param responseFormat + * @param jsonBody + * @param requestMethod + * @return String + */ + public String sendRESTRequest(String fullURI, Map hardCodedHeaderMap, + Map httpResponseCodeMap, + REST_RESPONSE_FORMAT responseFormat, + String jsonBody, + RESQUEST_METHOD requestMethod ){ + + String responseString = null; + HttpURLConnection connection = null; + try { + + URL url = new URL(fullURI); + + // + // Open up the connection + // + connection = (HttpURLConnection)url.openConnection(); + // + // Setup our method and headers + // + connection.setRequestMethod(requestMethod.toString()); + + connection.setUseCaches(false); + + // add hard-coded headers + for (String headerName : hardCodedHeaderMap.keySet()) { + connection.addRequestProperty(headerName, hardCodedHeaderMap.get(headerName)); + } + + + + if (jsonBody != null){ + connection.setDoInput(true); + connection.setDoOutput(true); + OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream()); + out.write(jsonBody); + out.flush(); + out.close(); + } else{ + connection.connect(); + } + + int responseCode = connection.getResponseCode(); + + // check that the response is one we expected (and get the associated value at the same time) + responseString = httpResponseCodeMap.get(responseCode); + if (responseString == null) { + // the response was not configured, meaning it is unexpected and therefore an error + LOGGER.error("Unexpected HTTP response code '" + responseCode + "' from RESTful Server"); + return ERROR_RECEIVED + " code" + responseCode + " from RESTful Server"; + } + + // if the response is contained only in the http code we are done. Otherwise we need to read the body + if (responseFormat == REST_RESPONSE_FORMAT.httpResponseCode) { + return responseString; + } + + // Need to read the body and return that as the responseString. + + responseString = null; + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); + scanner.useDelimiter("\\A"); + responseString = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + LOGGER.debug("RESTful body: " + responseString); + return responseString; + + } catch (Exception e) { + LOGGER.error("HTTP Request/Response from RESTFUL server: " + e); + responseString = ERROR_RECEIVED + e; + } finally { + // cleanup the connection + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = null; + try { + is = connection.getInputStream(); + } catch (Exception e1) { + // ignore this + } + if (is != null) { + is.close(); + } + + } catch (IOException ex) { + LOGGER.error("Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + return responseString; + + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyContainer.java new file mode 100644 index 000000000..fdca336ea --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyContainer.java @@ -0,0 +1,121 @@ +/*- + * ============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.utils; + +import java.io.Serializable; +import java.util.Collection; +import java.util.List; + + +public interface PolicyContainer extends Serializable{ + + public Collection getContainerPropertyIds(); + + public Collection getItemIds(); + + public Class getType(Object propertyId); + + public int size(); + + public boolean containsId(Object itemId); + + public Object addItem() throws UnsupportedOperationException; + + public boolean removeItem(Object itemId) + throws UnsupportedOperationException; + + public boolean addContainerProperty(Object propertyId, Class type, + Object defaultValue) throws UnsupportedOperationException; + + public boolean removeContainerProperty(Object propertyId) + throws UnsupportedOperationException; + + public boolean removeAllItems() throws UnsupportedOperationException; + + public interface Ordered extends PolicyContainer { + + public Object nextItemId(Object itemId); + + public Object prevItemId(Object itemId); + + public Object firstItemId(); + + public Object lastItemId(); + + public boolean isFirstId(Object itemId); + + public boolean isLastId(Object itemId); + + public Object addItemAfter(Object previousItemId) + throws UnsupportedOperationException; + + } + + + public interface Indexed extends Ordered { + + public int indexOfId(Object itemId); + + public Object getIdByIndex(int index); + + public List getItemIds(int startIndex, int numberOfItems); + + public Object addItemAt(int index) throws UnsupportedOperationException; + + public interface ItemAddEvent extends ItemSetChangeEvent { + + public Object getFirstItemId(); + + public int getFirstIndex(); + + public int getAddedItemsCount(); + } + + + public interface ItemRemoveEvent extends ItemSetChangeEvent { + + public Object getFirstItemId(); + + public int getFirstIndex(); + + public int getRemovedItemsCount(); + } + } + + public interface ItemSetChangeEvent extends Serializable { + + public PolicyContainer getContainer(); + } + + public interface ItemSetChangeListener extends Serializable { + + public void containerItemSetChange(PolicyContainer.ItemSetChangeEvent event); + } + + public interface ItemSetChangeNotifier extends Serializable { + + public void addItemSetChangeListener( + PolicyContainer.ItemSetChangeListener listener); + + public void removeItemSetChangeListener( + PolicyContainer.ItemSetChangeListener listener); + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java new file mode 100644 index 000000000..934c30564 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/PolicyItemSetChangeNotifier.java @@ -0,0 +1,95 @@ +/*- + * ============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.utils; + + +import java.io.Serializable; +import java.util.Collection; +import java.util.EventObject; +import java.util.LinkedList; + +import org.openecomp.policy.utils.PolicyContainer.ItemSetChangeEvent; +import org.openecomp.policy.utils.PolicyContainer.ItemSetChangeListener; + + + +public class PolicyItemSetChangeNotifier implements PolicyContainer.ItemSetChangeNotifier { + private static final long serialVersionUID = 1L; + private Collection itemSetChangeListeners = null; + private PolicyContainer container = null; + + public PolicyItemSetChangeNotifier() { + } + + protected void setContainer(PolicyContainer c) { + this.container = c; + } + + @Override + public void addItemSetChangeListener(ItemSetChangeListener listener) { + if (getItemSetChangeListeners() == null) { + setItemSetChangeListeners(new LinkedList()); + } + getItemSetChangeListeners().add(listener); } + + @Override + public void removeItemSetChangeListener(ItemSetChangeListener listener) { + if (getItemSetChangeListeners() != null) { + getItemSetChangeListeners().remove(listener); + } + } + + protected static class BaseItemSetChangeEvent extends EventObject implements + PolicyContainer.ItemSetChangeEvent, Serializable { + private static final long serialVersionUID = 1L; + + protected BaseItemSetChangeEvent(PolicyContainer source) { + super(source); + } + + @Override + public PolicyContainer getContainer() { + return (PolicyContainer) getSource(); + } + } + + protected void setItemSetChangeListeners( + Collection itemSetChangeListeners) { + this.itemSetChangeListeners = itemSetChangeListeners; + } + protected Collection getItemSetChangeListeners() { + return itemSetChangeListeners; + } + + protected void fireItemSetChange() { + fireItemSetChange(new BaseItemSetChangeEvent(this.container)); + } + + protected void fireItemSetChange(ItemSetChangeEvent event) { + if (getItemSetChangeListeners() != null) { + final Object[] l = getItemSetChangeListeners().toArray(); + for (int i = 0; i < l.length; i++) { + ((PolicyContainer.ItemSetChangeListener) l[i]) + .containerItemSetChange(event); + } + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java new file mode 100644 index 000000000..0abd874f6 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/openecomp/policy/utils/XACMLPolicyWriterWithPapNotify.java @@ -0,0 +1,483 @@ +/*- + * ============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.utils; + + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.nio.file.DirectoryNotEmptyException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Base64; +import java.util.UUID; + +import org.openecomp.policy.rest.XACMLRestProperties; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyWriter; +import com.att.research.xacml.util.XACMLProperties; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +/** + * Helper static class that wraps XACMLPolicyWriter + * + * + */ +public class XACMLPolicyWriterWithPapNotify{ + private static final Logger LOGGER = FlexLogger.getLogger(XACMLPolicyWriterWithPapNotify.class); + + /** + * Helper static class that does the work to write a policy set to a file on disk and notify PAP + * + * + */ + public static Path writePolicyFile(Path filename, PolicySetType policySet) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)" + + "\nfilename = " + filename + + "\npolicySet = " + policySet); + } + //write to file + Path path = XACMLPolicyWriter.writePolicyFile(filename, policySet); + + if(path!=null){ + //write to DB + if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){ + return path; + }else{ + //write to DB failed. So, delete the file + try{ + Files.deleteIfExists(path); + }catch(DirectoryNotEmptyException e){ + //We are trying to delete a directory and it is not empty + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nDirectoryNotEmptyException for path = " + path + + "\nException message = " + e); + }catch(IOException e) { + // File permission problems are caught here. + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nIOException for path = " + path + + "\nException message = " + e); + }catch(Exception e){ + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nException for path = " + path + + "\nException message = " + e); + } + return null; + } + + }else{ + return null; + } + } + + /** + * Helper static class that does the work to write a policy set to an output stream and notify PAP + * + * + */ + public static void writePolicyFile(OutputStream os, PolicySetType policySet) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicySetType policySet)" + + "\nos = " + os + + "\npolicySet = " + policySet); + } + //Only used for writing a byte array output stream for a message. No file is written + XACMLPolicyWriter.writePolicyFile(os, policySet); + } + + /** + * Helper static class that does the work to write a policy to a file on disk. + * + * + */ + public static Path writePolicyFile(Path filename, PolicyType policy) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicyType policy)" + + "\nfilename = " + filename + + "\npolicy = " + policy); + } + + //write to file + Path path = XACMLPolicyWriter.writePolicyFile(filename, policy); + + if(path!=null){ + //write to DB + if(notifyPapOfCreateUpdate(filename.toAbsolutePath().toString())){ + return path; + }else{ + //write to DB failed so delete the file + try{ + Files.deleteIfExists(path); + }catch(DirectoryNotEmptyException e){ + //We are trying to delete a directory and it is not empty + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet)Files.deleteIfExists(path) :" + + "\nDirectoryNotEmptyException for path = " + path + + "\nException message = " + e); + }catch(IOException e) { + // File permission problems are caught here. + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nIOException for path = " + path + + "\nException message = " + e); + }catch(Exception e){ + LOGGER.error("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(Path filename, PolicySetType policySet): Files.deleteIfExists(path)" + + "\nException for path = " + path + + "\nException message = " + e); + } + return null; + } + + }else{ + return null; + } + } + + + /** + * Helper static class that does the work to write a policy to a file on disk. + * + * + */ + public static InputStream getXmlAsInputStream(PolicyType policy) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.getXmlAsInputStream(PolicyType policy)" + + "\npolicy = " + policy); + } + return XACMLPolicyWriter.getXmlAsInputStream(policy); + } + /** + * Helper static class that does the work to write a policy set to an output stream. + * + * + */ + public static void writePolicyFile(OutputStream os, PolicyType policy) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.writePolicyFile(OutputStream os, PolicyType policy)" + + "\nos = " + os + + "\npolicy = " + policy); + } + //There are no references to this and if there were, it would most likely be used in an http message + XACMLPolicyWriter.writePolicyFile(os, policy); + } + + public static String changeFileNameInXmlWhenRenamePolicy(Path filename) { + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(Path filename)" + + "\nfilename = " + filename); + } + return XACMLPolicyWriter.changeFileNameInXmlWhenRenamePolicy(filename); + } + + public static boolean notifyPapOfPolicyRename(String oldPolicyName, String newPolicyName){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " + + "\npolicyToCreateUpdate = " + " "); + } + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + URL url; + try { + url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?oldPolicyName="+ URLEncoder.encode(oldPolicyName, "UTF-8")+"&newPolicyName="+URLEncoder.encode(newPolicyName,"UTF-8")); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nnotifyPapOfCreateUpdate: URL = " + url); + } + } catch (MalformedURLException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nMalformedURLException message = " + e); + + return false; + } catch (UnsupportedEncodingException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nUnsupportedEncodingException message = " + e); + + return false; + } + // + // Open up the connection + // + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nurl.openConnection() IOException message = " + e); + return false; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("PUT"); + } catch (ProtocolException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e); + connection.disconnect(); + return false; + } + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("requestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + connection.connect(); + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.connect() IOException message = " + e); + connection.disconnect(); + return false; + } + try { + int responseCode = connection.getResponseCode(); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() = " + responseCode); + } + if (responseCode == 200) { + connection.disconnect(); + return true; + } else { + connection.disconnect(); + return false; + } + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() IOException message = " + e); + connection.disconnect(); + return false; + } + } + + public static boolean notifyPapOfDelete(String policyToDelete){ + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + //loggingContext.setRequestID(requestID.toString()); + //loggingContext.transactionStarted(); + String papUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + if(papUrl == null){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "PAP url property does not exist"); + return false; + } + String urlString = ""; + try{ + urlString = papUrl+"?groupId=0&isDeleteNotify=1&policyToDelete="+ URLEncoder.encode(policyToDelete, "UTF-8"); + } catch(UnsupportedEncodingException e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Invalid encoding: UTF-8", e); + return false; + } + URL url; + try { + url = new URL(urlString); + } catch (MalformedURLException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + + "Error parsing PAP url: " + + urlString + , e); + return false; + } + // + // Open up the connection + // + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error opening HttpURLConnection to: " + + url.toString() + , e); + return false; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("DELETE"); + } catch (ProtocolException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + + "Invalid request method: DELETE", e); + connection.disconnect(); + return false; + } + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("requestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + connection.connect(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error connecting HttpURLConnection to: " + + connection.getURL().toString() + , e); + connection.disconnect(); + return false; + } + try { + if (connection.getResponseCode() == 200) { + connection.disconnect(); + //worked + return true; + } else { + connection.disconnect(); + return false; + } + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "Error getting HttpUrlConnection response code for: " + + connection.getURL().toString() + , e); + connection.disconnect(); + return false; + } + } + + public static boolean notifyPapOfCreateUpdate(String policyToCreateUpdate){ + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nXACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(String policyToCreateUpdate) " + + "\npolicyToCreateUpdate = " + policyToCreateUpdate); + } + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID)+":"+XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS)).getBytes(StandardCharsets.UTF_8)); + HttpURLConnection connection = null; + UUID requestID = UUID.randomUUID(); + //loggingContext.setRequestID(requestID.toString()); + //loggingContext.transactionStarted(); + URL url; + try { + url = new URL(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL)+"?policyToCreateUpdate="+ URLEncoder.encode(policyToCreateUpdate, "UTF-8")); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nnotifyPapOfCreateUpdate: URL = " + url); + } + } catch (MalformedURLException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nMalformedURLException message = " + e); + + return false; + } catch (UnsupportedEncodingException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nUnsupportedEncodingException message = " + e); + + return false; + } + // + // Open up the connection + // + try { + connection = (HttpURLConnection)url.openConnection(); + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nurl.openConnection() IOException message = " + e); + return false; + } + // + // Setup our method and headers + // + try { + connection.setRequestMethod("PUT"); + } catch (ProtocolException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.setRequestMethod(PUT) ProtocolException message = " + e); + connection.disconnect(); + return false; + } + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setRequestProperty("Accept", "text/x-java-properties"); + connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setRequestProperty("requestID", requestID.toString()); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setDoOutput(true); + connection.setDoInput(true); + try { + connection.connect(); + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.connect() IOException message = " + e); + connection.disconnect(); + return false; + } + try { + int responseCode = connection.getResponseCode(); + if(LOGGER.isDebugEnabled()){ + LOGGER.debug("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() = " + responseCode); + } + if (responseCode == 200) { + connection.disconnect(); + return true; + } else { + connection.disconnect(); + return false; + } + } catch (IOException e) { + LOGGER.error("\nnotifyPapOfCreateUpdate(String policyToCreateUpdate)" + + "\nconnection.getResponseCode() IOException message = " + e); + connection.disconnect(); + return false; + } + } +} -- cgit 1.2.3-korg