From 073cc188efe9abb4c010cf674e34e2cf46ef1c52 Mon Sep 17 00:00:00 2001 From: Guo Ruijing Date: Mon, 31 Jul 2017 08:47:35 +0000 Subject: [POLICY-73] replace openecomp for policy-engine Change-Id: I54072f6bcd388c0e05562614ee89b4ae7ad67004 Signed-off-by: Guo Ruijing Signed-off-by: Pamela Dragosh --- .../main/java/org/onap/policy/admin/CheckPDP.java | 181 +++ .../java/org/onap/policy/admin/PolicyAdapter.java | 116 ++ .../onap/policy/admin/PolicyManagerServlet.java | 1477 ++++++++++++++++++ .../onap/policy/admin/PolicyNotificationMail.java | 163 ++ .../onap/policy/admin/PolicyRestController.java | 443 ++++++ .../policy/admin/PolicyUserInfoController.java | 62 + .../org/onap/policy/admin/RESTfulPAPEngine.java | 517 +++++++ .../policy/components/HumanPolicyComponent.java | 991 ++++++++++++ .../org/onap/policy/conf/HibernateSession.java | 63 + .../policy/controller/ActionPolicyController.java | 268 ++++ .../onap/policy/controller/AdminTabController.java | 119 ++ .../onap/policy/controller/AutoPushController.java | 377 +++++ .../controller/CreateBRMSParamController.java | 551 +++++++ .../policy/controller/CreateBRMSRawController.java | 172 +++ .../CreateClosedLoopFaultController.java | 709 +++++++++ .../controller/CreateClosedLoopPMController.java | 208 +++ .../CreateDcaeMicroServiceController.java | 1622 ++++++++++++++++++++ .../controller/CreateFirewallController.java | 929 +++++++++++ .../policy/controller/CreatePolicyController.java | 163 ++ .../policy/controller/DashboardController.java | 430 ++++++ .../controller/DecisionPolicyController.java | 361 +++++ .../org/onap/policy/controller/PDPController.java | 394 +++++ .../onap/policy/controller/PolicyController.java | 696 +++++++++ .../PolicyExportAndImportController.java | 384 +++++ .../controller/PolicyNotificationController.java | 122 ++ .../policy/controller/PolicyRolesController.java | 167 ++ .../controller/PolicyValidationController.java | 776 ++++++++++ .../java/org/onap/policy/dao/SystemLogDbDao.java | 33 + .../org/onap/policy/daoImp/CommonClassDaoImpl.java | 382 +++++ .../org/onap/policy/daoImp/SystemLogDbDaoImpl.java | 93 ++ .../org/onap/policy/model/PDPGroupContainer.java | 522 +++++++ .../org/onap/policy/model/PDPPolicyContainer.java | 348 +++++ .../src/main/java/org/onap/policy/model/Roles.java | 99 ++ .../onap/policy/utils/ConfigurableRESTUtils.java | 163 ++ .../org/onap/policy/utils/PolicyContainer.java | 121 ++ .../policy/utils/PolicyItemSetChangeNotifier.java | 95 ++ .../utils/XACMLPolicyWriterWithPapNotify.java | 483 ++++++ 37 files changed, 14800 insertions(+) create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyContainer.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyItemSetChangeNotifier.java create mode 100644 POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java (limited to 'POLICY-SDK-APP/src/main/java/org/onap') diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java new file mode 100644 index 000000000..f983c6650 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/CheckPDP.java @@ -0,0 +1,181 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.admin; + + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.xacml.api.XACMLErrorConstants; + +import com.att.research.xacml.util.XACMLProperties; + +public class CheckPDP { + private static Path pdpPath = null; + private static Long oldModified = null; + private static HashMap pdpMap = null; + private static final Logger LOGGER = FlexLogger.getLogger(CheckPDP.class); + + private CheckPDP(){ + //default constructor + } + public static boolean validateID(String id) { + // ReadFile + try { + readFile(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + return false; + } + // Check ID + return (pdpMap.containsKey(id))? true: false; + } + + private static void readFile(){ + String pdpFile = null; + Long newModified = null; + try{ + pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); + }catch (Exception e){ + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File" + e); + return; + } + if (pdpFile == null) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); + } + if (pdpPath == null) { + pdpPath = Paths.get(pdpFile); + if (!pdpPath.toFile().exists()) { + LOGGER.error(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); + } + } + // Check if File is updated recently + else { + newModified = pdpPath.toFile().lastModified(); + if (!newModified.equals(oldModified)) { + // File has been updated. + readProps(); + } + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void readProps() { + Properties pdpProp = null; + pdpProp = new Properties(); + try { + InputStream in = new FileInputStream(pdpPath.toFile()); + oldModified = pdpPath.toFile().lastModified(); + pdpProp.load(in); + // 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) { + loadPDPProperties(propKey, pdpProp); + } + if (pdpMap == null || pdpMap.isEmpty()) { + LOGGER.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); + } + in.close(); + } catch (IOException e) { + LOGGER.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + } + + private static void loadPDPProperties(String propKey, Properties pdpProp){ + if (propKey.startsWith("PDP_URL")) { + String check_val = pdpProp.getProperty(propKey); + if (check_val == null) { + LOGGER.error("Properties file doesn't have the PDP_URL parameter"); + } + if (check_val != null && 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++; + } + } + } + } + + private static void readPDPParam(String pdpVal){ + 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); + } + }else{ + LOGGER.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); + } + } + + 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/onap/policy/admin/PolicyAdapter.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java new file mode 100644 index 000000000..ee4cbcc03 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyAdapter.java @@ -0,0 +1,116 @@ +package org.onap.policy.admin; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.ActionPolicyController; +import org.onap.policy.controller.CreateBRMSParamController; +import org.onap.policy.controller.CreateBRMSRawController; +import org.onap.policy.controller.CreateClosedLoopFaultController; +import org.onap.policy.controller.CreateClosedLoopPMController; +import org.onap.policy.controller.CreateDcaeMicroServiceController; +import org.onap.policy.controller.CreateFirewallController; +import org.onap.policy.controller.CreatePolicyController; +import org.onap.policy.controller.DecisionPolicyController; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.PolicyEntity; + +import com.att.research.xacml.util.XACMLProperties; + +public class PolicyAdapter { + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyAdapter.class); + + 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) { + LOGGER.error("Exception Occured"+e); + } + return null; + } + + + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java new file mode 100644 index 000000000..036d13aa6 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyManagerServlet.java @@ -0,0 +1,1477 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.components.HumanPolicyComponent; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.controller.PolicyExportAndImportController; +import org.onap.policy.model.Roles; +import org.onap.policy.rest.XACMLRest; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.ActionBodyEntity; +import org.onap.policy.rest.jpa.ConfigurationDataEntity; +import org.onap.policy.rest.jpa.PolicyEditorScopes; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.utils.PolicyUtils; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.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, SEARCHLIST + } + + private static PolicyController policyController; + public synchronized PolicyController getPolicyController() { + return policyController; + } + + public synchronized static void setPolicyController(PolicyController policyController) { + PolicyManagerServlet.policyController = policyController; + } + + 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; + private static String testUserId = null; + + 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; + JsonReader jsonReader = null; + String location = closedLoopJsonLocation.toString(); + try { + inputStream = new FileInputStream(location); + if (location.endsWith("json")) { + 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); + } + } + } catch (FileNotFoundException e) { + LOGGER.error("Exception Occured while initializing the JSONConfig file"+e); + }finally{ + try { + if(inputStream != null){ + inputStream.close(); + } + if(jsonReader != null){ + jsonReader.close(); + } + } catch (IOException e) { + LOGGER.error("Exception Occured while closing the File InputStream"+e); + } + } + } + + @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) { + try { + setError(e, response); + }catch(Exception e1){ + LOGGER.error("Exception Occured"+e1); + } + } + } + + //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) { + LOGGER.error("Exception Occured"+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")){ + OutputStream outputStream = null; + try{ + File file = new File(item.getName()); + 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); + }finally{ + if(outputStream != null){ + outputStream.close(); + } + } + } + } + } + + JSONObject responseJsonObject = null; + responseJsonObject = this.success(); + response.setContentType(CONTENTTYPE); + 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: + case ADDSUBSCOPE: + responseJsonObject = addFolder(params, request); + break; + case COPY: + responseJsonObject = copy(params, request); + break; + case DELETE: + responseJsonObject = delete(params, request); + break; + case EDITFILE: + 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 SWITCHVERSION: + responseJsonObject = switchVersion(params, request); + break; + case SEARCHLIST: + responseJsonObject = searchPolicyList(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(CONTENTTYPE); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } + + private JSONObject searchPolicyList(JSONObject params, HttpServletRequest request) { + Set scopes = null; + List roles = null; + List policyData = new ArrayList<>(); + JSONArray policyList = null; + if(params.has("policyList")){ + policyList = (JSONArray) params.get("policyList"); + } + PolicyController controller = getPolicyControllerInstance(); + List resultList = new ArrayList<>(); + 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 = controller.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"); + } + Set tempScopes = scopes; + for(String scope : tempScopes){ + List scopesList = queryPolicyEditorScopes(scope); + if(!scopesList.isEmpty()){ + for(int i = 0; i < scopesList.size(); i++){ + PolicyEditorScopes tempScope = (PolicyEditorScopes) scopesList.get(i); + scopes.add(tempScope.getScopeName()); + } + } + } + } + if(policyList!= null){ + for(int i = 0; i < policyList.length(); i++){ + String policyName = policyList.get(i).toString().replace(".xml", ""); + String version = policyName.substring(policyName.lastIndexOf(".")+1); + policyName = policyName.substring(0, policyName.lastIndexOf(".")).replace(".", File.separator); + if(policyName.contains("\\")){ + policyName = policyName.replace("\\", "\\\\"); + } + String policyVersionQuery = "From PolicyVersion where policy_name ='"+policyName+"' and active_version = '"+version+"'and id >0"; + List activeData = controller.getDataByQuery(policyVersionQuery); + if(!activeData.isEmpty()){ + PolicyVersion policy = (PolicyVersion) activeData.get(0); + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().replace(File.separator, "/")); + 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 (roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ){ + policyData = controller.getData(PolicyVersion.class); + }else{ + List filterdatas = controller.getData(PolicyVersion.class); + for(Object filter : filterdatas){ + PolicyVersion filterdata = (PolicyVersion) filter; + try{ + String scopeName = filterdata.getPolicyName().substring(0, filterdata.getPolicyName().lastIndexOf(File.separator)); + if(scopes.contains(scopeName)){ + policyData.add(filterdata); + } + }catch(Exception e){ + LOGGER.error("Exception occured while filtering policyversion data"+e); + } + } + } + + if(!policyData.isEmpty()){ + for(int i =0; i < policyData.size(); i++){ + PolicyVersion policy = (PolicyVersion) policyData.get(i); + JSONObject el = new JSONObject(); + el.put("name", policy.getPolicyName().replace(File.separator, "/")); + 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); + } + } + } + }catch(Exception e){ + LOGGER.error("Exception occured while reading policy Data from Policy Version table for Policy Search Data"+e); + } + + return new JSONObject().put(RESULT, resultList); + } + + //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 = getPolicyControllerInstance(); + 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("/", "."); + policyName = path; + } + 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 = getPolicyControllerInstance(); + String[] split = path.split(":"); + String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; + List queryData = controller.getDataByQuery(query); + if(!queryData.isEmpty()){ + PolicyEntity entity = (PolicyEntity) queryData.get(0); + File temp = null; + BufferedWriter bw = null; + try { + temp = File.createTempFile(policyName, ".tmp"); + bw = new BufferedWriter(new FileWriter(temp)); + bw.write(entity.getPolicyData()); + bw.close(); + object = HumanPolicyComponent.DescribePolicy(temp); + } catch (IOException e) { + LOGGER.error("Exception Occured while Describing the Policy"+e); + }finally{ + if(temp != null){ + temp.delete(); + } + if(bw != null){ + try { + bw.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured while Closing the File Writer"+e); + } + } + } + }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 { + PolicyController controller = getPolicyControllerInstance(); + //Get the Login Id of the User from Request + String testUserID = getTestUserId(); + String userId = testUserID != null ? testUserID : UserUtils.getUserSession(request).getOrgUserId(); + //Check if the Role and Scope Size are Null get the values from db. + List userRoles = controller.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()); + } + } + } + + List resultList = new ArrayList<>(); + boolean onlyFolders = params.getBoolean("onlyFolders"); + String path = params.getString("path"); + if(path.contains("..xml")){ + path = path.replaceAll("..xml", "").trim(); + } + + 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"); + }else{ + if(!"/".equals(path)){ + String tempScope = path.substring(1, path.length()); + tempScope = tempScope.replace("/", File.separator); + scopes.add(tempScope); + } + } + } + + 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()); + if(!scopesList.isEmpty()){ + 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 = getPolicyControllerInstance(); + 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 = getPolicyControllerInstance(); + 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 = getPolicyControllerInstance(); + UserInfo userInfo = (UserInfo) controller.getEntityItem(UserInfo.class, "userLoginId", loginId); + if(userInfo == null){ + return SUPERADMIN; + } + return userInfo.getUserName(); + } + + //Rename Policy + private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException { + try { + boolean isActive = false; + List policyActiveInPDP = new ArrayList<>(); + Set scopeOfPolicyActiveInPDP = new HashSet<>(); + 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")){ + JSONObject result = policyRename(oldPath, newPath, userId); + if(!(Boolean)(result.getJSONObject("result").get("success"))){ + return result; + } + }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 = getPolicyControllerInstance(); + 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); + JSONObject result = policyRename(policyOldPath, policyNewPath, userId); + if(!(Boolean)(result.getJSONObject("result").get("success"))){ + isActive = true; + policyActiveInPDP.add(policyOldPath); + String scope = policyOldPath.substring(0, policyOldPath.lastIndexOf("/")); + scopeOfPolicyActiveInPDP.add(scope.replace("/", File.separator)); + } + } + boolean rename = false; + if(activePolicies.size() != policyActiveInPDP.size()){ + rename = true; + } + + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + if(policyActiveInPDP.size() == 0){ + renameScope(scopesList, scopeName, newScopeName, controller); + }else if(rename){ + renameScope(scopesList, scopeName, newScopeName, controller); + for(String scope : scopeOfPolicyActiveInPDP){ + PolicyEditorScopes editorScopeEntity = new PolicyEditorScopes(); + editorScopeEntity.setScopeName(scope.replace("\\", "\\\\\\\\")); + editorScopeEntity.setUserCreatedBy(userInfo); + editorScopeEntity.setUserModifiedBy(userInfo); + controller.saveData(editorScopeEntity); + } + } + if(isActive){ + return error("The Following policies rename failed. Since they are active in PDP Groups" +policyActiveInPDP); + } + } + return success(); + } catch (Exception e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); + return error(e.getMessage()); + } + } + + private void renameScope(List scopesList, String scopeName, String newScopeName, PolicyController controller){ + 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); + } + } + + private JSONObject policyRename(String oldPath, String newPath, String userId) throws ServletException { + try { + PolicyEntity entity = null; + PolicyController controller = getPolicyControllerInstance(); + + 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]+"'"; + List queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + entity = (PolicyEntity) queryData.get(0); + return error("Policy rename failed. Since, the policy with same name already exists."); + } + + //Query the Policy Entity with oldPolicy Name + String policyEntityCheck = oldPolicySplit[1].substring(0, oldPolicySplit[1].indexOf(".")); + String oldpolicyEntityquery = "FROM PolicyEntity where policyName like '"+policyEntityCheck+"%' and scope ='"+oldPolicySplit[0]+"'"; + List oldEntityData = controller.getDataByQuery(oldpolicyEntityquery); + if(!oldEntityData.isEmpty()){ + String groupQuery = "FROM PolicyGroupEntity where ("; + for(int i=0; i groupEntityData = controller.getDataByQuery(groupQuery); + if(groupEntityData.size() > 0){ + return error("Policy rename failed. Since the policy or its version is active in PDP Groups."); + } + for(int i=0; i queryData = controller.getDataByQuery(policyEntityquery); + if(!queryData.isEmpty()){ + return error("Policy already exists with same name"); + } + + //Query the Policy Entity with oldPolicy Name + policyEntityquery = "FROM PolicyEntity where policyName = '"+oldPolicySplit[1]+"' and scope ='"+oldPolicySplit[0]+"'"; + 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 = getPolicyControllerInstance(); + 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); + String activePolicyName = null; + boolean pdpCheck = false; + 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.isEmpty()){ + pdpCheck = true; + activePolicyName = policyEntity.getScope() +"."+ policyEntity.getPolicyName(); + }else{ + //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"); + if(pdpCheck){ + //Delete from policyVersion table + String getActivePDPPolicyVersion = activePolicyName.replace(".xml", ""); + getActivePDPPolicyVersion = getActivePDPPolicyVersion.substring(getActivePDPPolicyVersion.lastIndexOf(".")+1); + String policyVersionQuery = "update PolicyVersion set active_version='"+getActivePDPPolicyVersion+"' , highest_version='"+getActivePDPPolicyVersion+"' where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + controller.executeQuery(policyVersionQuery); + } + return error("Policies with Same name has been deleted. Except the Active Policy in PDP. PolicyName: "+activePolicyName); + }else{ + //No Active Policy in PDP. So, deleting all entries from policyVersion table + String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +policyNamewithoutExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + controller.executeQuery(policyVersionQuery); + } + } + }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()+"' and policyid > 0"; + List groupobject = controller.getDataByQuery(groupEntityquery); + if(groupobject.isEmpty()){ + //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 && policyEntityVersion != version){ + 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{ + List activePoliciesInPDP = new ArrayList(); + 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.isEmpty()){ + pdpCheck = true; + activePoliciesInPDP.add(policyEntity.getScope()+"."+policyEntity.getPolicyName()); + }else{ + //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"; + controller.executeQuery(policyVersionQuery); + + //Policy Notification + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(path); + entity.setModifiedBy(userId); + controller.watchPolicyFunction(entity, path, "DeleteScope"); + if(pdpCheck){ + //Add Active Policies List to PolicyVersionTable + for(int i =0; i < activePoliciesInPDP.size(); i++){ + String activePDPPolicyName = activePoliciesInPDP.get(i).replace(".xml", ""); + int activePDPPolicyVersion = Integer.parseInt(activePDPPolicyName.substring(activePDPPolicyName.lastIndexOf(".")+1)); + activePDPPolicyName = activePDPPolicyName.substring(0, activePDPPolicyName.lastIndexOf(".")).replace(".", File.separator); + PolicyVersion insertactivePDPVersion = new PolicyVersion(); + insertactivePDPVersion.setPolicyName(activePDPPolicyName); + insertactivePDPVersion.setHigherVersion(activePDPPolicyVersion); + insertactivePDPVersion.setActiveVersion(activePDPPolicyVersion); + insertactivePDPVersion.setCreatedBy(userId); + insertactivePDPVersion.setModifiedBy(userId); + controller.saveData(insertactivePDPVersion); + } + + return error("All the Policies has been deleted in Scope. Except the following list of Policies:"+activePoliciesInPDP); + }else{ + String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + controller.executeQuery(policyScopeQuery); + } + }else{ + String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+path.replace("\\", "\\\\")+"%' and id >0"; + controller.executeQuery(policyScopeQuery); + } + } + 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 = getPolicyControllerInstance(); + 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 = getPolicyControllerInstance(); + 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("")){ + if(name.startsWith(File.separator)){ + name = name.substring(1); + } + PolicyEditorScopes entity = (PolicyEditorScopes) controller.getEntityItem(PolicyEditorScopes.class, "scopeName", name); + if(entity == null){ + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + PolicyEditorScopes newScope = new PolicyEditorScopes(); + newScope.setScopeName(name); + 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); + } + } + + private PolicyController getPolicyControllerInstance(){ + return policyController != null ? getPolicyController() : new PolicyController(); + } + + public String getTestUserId() { + return testUserId; + } + + public static void setTestUserId(String testUserId) { + PolicyManagerServlet.testUserId = testUserId; + } +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java new file mode 100644 index 000000000..bf89c01ff --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyNotificationMail.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.rest.jpa.WatchPolicyNotificationTable; +import org.onap.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 policyLogger = FlexLogger.getLogger(PolicyNotificationMail.class); + + @Bean + public JavaMailSenderImpl javaMailSenderImpl(){ + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost(PolicyController.getSmtpHost()); + mailSender.setPort(Integer.parseInt(PolicyController.getSmtpPort())); + mailSender.setUsername(PolicyController.getSmtpUsername()); + mailSender.setPassword(PolicyController.getSmtpPassword()); + 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; + } + + public void sendMail(PolicyVersion entityItem, String policyName, String mode, CommonClassDao policyNotificationDao) throws MessagingException { + String from = PolicyController.getSmtpUsername(); + String to = ""; + String subject = ""; + String message = ""; + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + if("EditPolicy".equalsIgnoreCase(mode)){ + subject = "Policy has been Updated : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " 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("Rename".equalsIgnoreCase(mode)){ + subject = "Policy has been Renamed : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " 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("DeleteAll".equalsIgnoreCase(mode)){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " 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("DeleteOne".equalsIgnoreCase(mode)){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " 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("DeleteScope".equalsIgnoreCase(mode)){ + subject = "Scope has been Deleted : "+entityItem.getPolicyName(); + message = "The Scope Which you are watching in " + PolicyController.getSmtpApplicationName() + " 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("SwitchVersion".equalsIgnoreCase(mode)){ + subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " 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("Move".equalsIgnoreCase(mode)){ + subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.getSmtpApplicationName() + " 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 = policyName; + 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 && !watchList.isEmpty()){ + for(Object watch : watchList){ + WatchPolicyNotificationTable list = (WatchPolicyNotificationTable) watch; + String watchPolicyName = list.getPolicyName(); + if(watchPolicyName.contains("Config_") || watchPolicyName.contains("Action_") || watchPolicyName.contains("Decision_")){ + if(watchPolicyName.equals(checkPolicyName)){ + sendFlag = true; + }else{ + sendFlag = false; + } + } + if(sendFlag){ + AnnotationConfigApplicationContext ctx = null; + try { + to = list.getLoginIds()+"@"+PolicyController.getSmtpEmailExtension(); + to = to.trim(); + ctx = new AnnotationConfigApplicationContext(); + ctx.register(PolicyNotificationMail.class); + ctx.refresh(); + JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class); + MimeMessage mimeMessage = mailSender.createMimeMessage(); + MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage); + mailMsg.setFrom(new InternetAddress(from, "Policy Notification System")); + mailMsg.setTo(to); + mailMsg.setSubject(subject); + mailMsg.setText(message); + mailSender.send(mimeMessage); + if(mode.equalsIgnoreCase("Rename") || mode.contains("Delete") || mode.contains("Move")){ + policyNotificationDao.delete(watch); + } + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e); + }finally{ + if(ctx != null){ + ctx.close(); + } + } + } + } + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java new file mode 100644 index 000000000..e99f35bde --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyRestController.java @@ -0,0 +1,443 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.ArrayList; +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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.CreateClosedLoopFaultController; +import org.onap.policy.controller.CreateDcaeMicroServiceController; +import org.onap.policy.controller.CreateFirewallController; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.utils.PolicyUtils; +import org.onap.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 policyLogger = FlexLogger.getLogger(PolicyRestController.class); + + private static final String modal = "model"; + private static final String importDictionary = "import_dictionary"; + + @Autowired + CommonClassDao commonClassDao; + + @RequestMapping(value={"/policycreation/save_policy"}, method={RequestMethod.POST}) + public void policyCreationController(HttpServletRequest request, HttpServletResponse response) { + String userId = UserUtils.getUserSession(request).getOrgUserId(); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + try{ + JsonNode root = mapper.readTree(request.getReader()); + + PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); + + if("file".equals(root.get(PolicyController.getPolicydata()).get(modal).get("type").toString().replace("\"", ""))){ + policyData.setEditPolicy(true); + } + if(root.get(PolicyController.getPolicydata()).get(modal).get("path").size() != 0){ + String dirName = ""; + for(int i = 0; i < root.get(PolicyController.getPolicydata()).get(modal).get("path").size(); i++){ + dirName = dirName.replace("\"", "") + root.get(PolicyController.getPolicydata()).get(modal).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(PolicyController.getPolicydata()).get(modal).get("name").toString().replace("\"", "")); + } + }else{ + String domain = root.get(PolicyController.getPolicydata()).get("model").get("name").toString(); + if(domain.contains("/")){ + domain = domain.substring(0, domain.lastIndexOf('/')).replace("/", File.separator); + } + domain = domain.replace("\"", ""); + policyData.setDomainDir(domain); + } + + if(policyData.getConfigPolicyType() != null){ + if("ClosedLoop_Fault".equalsIgnoreCase(policyData.getConfigPolicyType())){ + CreateClosedLoopFaultController faultController = new CreateClosedLoopFaultController(); + policyData = faultController.setDataToPolicyRestAdapter(policyData, root); + }else if("Firewall Config".equalsIgnoreCase(policyData.getConfigPolicyType())){ + CreateFirewallController fwController = new CreateFirewallController(); + policyData = fwController.setDataToPolicyRestAdapter(policyData); + }else if("Micro Service".equalsIgnoreCase(policyData.getConfigPolicyType())){ + CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); + policyData = msController.setDataToPolicyRestAdapter(policyData, root); + } + } + + policyData.setUserId(userId); + + String result; + String body = PolicyUtils.objectToJsonString(policyData); + String uri = request.getRequestURI(); + ResponseEntity responseEntity = sendToPAP(body, uri, HttpMethod.POST); + if(responseEntity != null && responseEntity.getBody().equals(HttpServletResponse.SC_CONFLICT)){ + result = "PolicyExists"; + }else if(responseEntity != null){ + result = responseEntity.getBody().toString(); + String policyName = responseEntity.getHeaders().get("policyName").get(0); + if(policyData.isEditPolicy() && "success".equalsIgnoreCase(result)){ + 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); + } + }else{ + result = "Response is null from PAP"; + } + + response.setCharacterEncoding(PolicyController.getCharacterencoding()); + response.setContentType(PolicyController.getContenttype()); + request.setCharacterEncoding(PolicyController.getCharacterencoding()); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(result); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + }catch(Exception e){ + policyLogger.error("Exception Occured while saving policy" , e); + } + } + + + private ResponseEntity sendToPAP(String body, String requestURI, HttpMethod method){ + String papUrl = PolicyController.getPapUrl(); + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + + 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", PolicyController.getContenttype()); + + RestTemplate restTemplate = new RestTemplate(); + HttpEntity requestEntity = new HttpEntity<>(body, headers); + ResponseEntity result = null; + HttpClientErrorException exception = null; + + try{ + result = restTemplate.exchange(papUrl + requestURI, method, requestEntity, String.class); + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); + exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); + if("409 Conflict".equals(e.getMessage())){ + return 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" ; + policyLogger.error(message); + } + if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){ + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + policyLogger.error(message); + } + if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){ + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception; + policyLogger.error(message); + } + String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + policyLogger.error(message); + } + return result; + } + + private String callPAP(HttpServletRequest request , String method, String uriValue){ + String uri = uriValue; + String boundary = null; + String papUrl = PolicyController.getPapUrl(); + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + + 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", PolicyController.getContenttype()); + + + HttpURLConnection connection = null; + List items; + FileItem item = null; + File file = null; + if(uri.contains(importDictionary)){ + 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) { + policyLogger.error("Exception Occured while calling PAP with import dictionary request"+e2); + } + } + + 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?action=delete&")){ + + if(!(uri.endsWith("set_BRMSParamData") || uri.contains(importDictionary))){ + connection.setRequestProperty("Content-Type",PolicyController.getContenttype()); + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = null; + try { + root = mapper.readTree(request.getReader()); + }catch (Exception e1) { + policyLogger.error("Exception Occured while calling PAP"+e1); + } + + 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 instanceof InputStream) { + // send current configuration + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy((InputStream) content, os); + if (policyLogger.isDebugEnabled()) { + policyLogger.debug("copied to output, bytes=" + count); + } + } + } + }else{ + if(uri.endsWith("set_BRMSParamData")){ + connection.setRequestProperty("Content-Type",PolicyController.getContenttype()); + 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()) { + if(item != null){ + 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(); + policyLogger.info("JSON response from PAP: " + responseJson); + return responseJson; + } + + } catch (Exception e) { + policyLogger.error("Exception Occured"+e); + }finally{ + if(file != null && file.exists() && file.delete()){ + policyLogger.info("File Deleted Successfully"); + } + 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 = connection.getInputStream(); + if (is != null) { + is.close(); + } + } catch (IOException ex) { + policyLogger.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){ + String uri = request.getRequestURI().replace("/getDictionary", ""); + String body = null; + ResponseEntity responseEntity = sendToPAP(null, uri, HttpMethod.GET); + if(responseEntity != null){ + body = responseEntity.getBody().toString(); + }else{ + body = ""; + } + try { + response.getWriter().write(body); + } catch (IOException e) { + policyLogger.error("Exception occured while getting Dictionary entries", e); + } + } + + @RequestMapping(value={"/saveDictionary/*/*"}, method={RequestMethod.POST}) + public ModelAndView saveDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + String uri = request.getRequestURI().replace("/saveDictionary", ""); + if(uri.contains(importDictionary)){ + String userId = UserUtils.getUserSession(request).getOrgUserId(); + uri = uri+ "?userId=" +userId; + } + String body = callPAP(request, "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, "POST", uri.replaceFirst("/", "").trim()); + response.getWriter().write(body); + return null; + } + + @RequestMapping(value={"/searchDictionary"}, method={RequestMethod.POST}) + public ModelAndView searchDictionaryController(HttpServletRequest request, HttpServletResponse response) throws Exception{ + Object resultList = null; + String uri = request.getRequestURI(); + try{ + String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + if(body.contains("CouldNotConnectException")){ + List data = new ArrayList<>(); + data.add("Elastic Search Server is down"); + resultList = data; + }else{ + JSONObject json = new JSONObject(body); + resultList = json.get("policyresult"); + } + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception Occured while querying Elastic Search: " + e); + List data = new ArrayList<>(); + data.add("Elastic Search Server is down"); + resultList = data; + } + + response.setCharacterEncoding(PolicyController.getCharacterencoding()); + response.setContentType(PolicyController.getContenttype()); + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + resultList + "}"); + out.write(j.toString()); + return null; + } + + @RequestMapping(value={"/searchPolicy"}, method={RequestMethod.POST}) + public ModelAndView searchPolicy(HttpServletRequest request, HttpServletResponse response) throws Exception{ + Object resultList = null; + String uri = request.getRequestURI()+"?action=search"; + String body = callPAP(request, "POST", uri.replaceFirst("/", "").trim()); + + JSONObject json = new JSONObject(body); + try{ + resultList = json.get("policyresult"); + }catch(Exception e){ + List data = new ArrayList<>(); + data.add("Elastic Search Server is down"); + resultList = data; + policyLogger.error("Exception Occured while searching for Policy in Elastic Database" +e); + } + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + JSONObject j = new JSONObject("{result: " + resultList + "}"); + out.write(j.toString()); + return null; + } + + public void deleteElasticData(String fileName){ + String uri = "searchPolicy?action=delete&policyName='"+fileName+"'"; + callPAP(null, "POST", uri.trim()); + } + +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java new file mode 100644 index 000000000..65312a957 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/PolicyUserInfoController.java @@ -0,0 +1,62 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +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{ + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyUserInfoController.class); + + @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) { + LOGGER.error("Exception Occured"+e); + } + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java new file mode 100644 index 000000000..d75af075d --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/admin/RESTfulPAPEngine.java @@ -0,0 +1,517 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; +import org.onap.policy.xacml.std.pap.StdPAPPolicy; +import org.onap.policy.xacml.std.pap.StdPDP; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier; +import org.onap.policy.xacml.std.pap.StdPDPPolicy; +import org.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.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); + + private static final String groupID = "groupId="; + + // + // 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 OnapPDPGroup getDefaultGroup() throws PAPException { + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "default="); + } + + @Override + public void SetDefaultGroup(OnapPDPGroup group) throws PAPException { + sendToPAP("POST", null, null, null, groupID + group.getId(), "default=true"); + } + + @SuppressWarnings("unchecked") + @Override + public Set getOnapPDPGroups() throws PAPException { + Set newGroupSet; + newGroupSet = (Set) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, groupID); + return Collections.unmodifiableSet(newGroupSet); + } + + + @Override + public OnapPDPGroup getGroup(String id) throws PAPException { + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID + id); + } + + @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() +e); + } + + 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(OnapPDPGroup 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(OnapPDPGroup group, OnapPDPGroup 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 OnapPDPGroup getPDPGroup(OnapPDP pdp) throws PAPException { + return getPDPGroup(pdp.getId()); + } + + + public OnapPDPGroup getPDPGroup(String pdpId) throws PAPException { + return (OnapPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, groupID, "pdpId=" + pdpId, "getPDPGroup="); + } + + @Override + public OnapPDP getPDP(String pdpId) throws PAPException { + return (OnapPDP)sendToPAP("GET", null, null, StdPDP.class, groupID, "pdpId=" + pdpId); + } + + @Override + public void newPDP(String id, OnapPDPGroup 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(OnapPDP pdp, OnapPDPGroup newGroup) throws PAPException { + sendToPAP("POST", null, null, null, groupID + newGroup.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void updatePDP(OnapPDP pdp) throws PAPException { + OnapPDPGroup group = getPDPGroup(pdp); + sendToPAP("PUT", pdp, null, null, groupID + group.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void removePDP(OnapPDP pdp) throws PAPException { + OnapPDPGroup 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, OnapPDPGroup 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, OnapPDPGroup 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, OnapPDPGroup 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, OnapPDPGroup 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(OnapPDP pdp) throws PAPException { + return (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class); + } + + + // + // 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); + 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 OnapPDP) && responseContentClass == StdPDPStatus.class) { + // Adjust the url and properties appropriately + String pdpID =((OnapPDP)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); + } + } 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 = connection.getInputStream(); + 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/onap/policy/components/HumanPolicyComponent.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java new file mode 100644 index 000000000..a0f1ba86d --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/components/HumanPolicyComponent.java @@ -0,0 +1,991 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.Path; +import java.nio.file.Paths; +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 org.apache.commons.io.FilenameUtils; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.jpa.FunctionDefinition; +import org.onap.policy.utils.XACMLPolicyWriterWithPapNotify; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.util.XACMLPolicyScanner; + +import com.att.research.xacml.api.AttributeValue; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.std.StdAttribute; +import com.att.research.xacml.std.StdAttributeValue; +import com.att.research.xacml.util.XACMLPolicyScanner.CallbackResult; +import com.att.research.xacml.util.XACMLPolicyScanner.SimpleCallback; + +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; + + + +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.onap.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; + + private HumanPolicyComponent(){ + //Default Constructor + } + + 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; + + } catch (IllegalArgumentException e) { + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "cannot build html area por policy", e); + } + 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 = Paths.get(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.getType() + "" + 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.setType(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()); + if(attribute != null){ + 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; + private String type; + public final String id; + + public AttributeIdentifiers(String category, String type, String id) { + this.category = category; + this.setType(type); + this.id = id; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java new file mode 100644 index 000000000..d70f199f0 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/conf/HibernateSession.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.conf; + +/* + * + * + * */ +import java.util.Properties; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.rest.jpa.SystemLogDB; + +@SuppressWarnings("deprecation") +public class HibernateSession{ + + private static final Logger LOGGER = FlexLogger.getLogger(HibernateSession.class); + + private static SessionFactory logSessionFactory; + + static { + try { + Properties prop= new Properties(); + prop.setProperty("hibernate.connection.url", PolicyController.getLogdbUrl()); + prop.setProperty("hibernate.connection.username", PolicyController.getLogdbUserName()); + prop.setProperty("hibernate.connection.password", PolicyController.getLogdbPassword()); + prop.setProperty("dialect", PolicyController.getLogdbDialect()); + prop.setProperty("hibernate.connection.driver_class", PolicyController.getLogdbDriver()); + prop.setProperty("show_sql", "false"); + logSessionFactory = new Configuration().addPackage("org.onap.policy.*").addProperties(prop) + .addAnnotatedClass(SystemLogDB.class).buildSessionFactory(); + } catch (Exception ex) { + LOGGER.error("Exception Occured while creating Log database Hibernate session"+ex); + } + } + public static Session getSession(){ + return logSessionFactory.openSession(); + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java new file mode 100644 index 000000000..0a985045d --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ActionPolicyController.java @@ -0,0 +1,268 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + +@Controller +@RequestMapping({"/"}) +public class ActionPolicyController extends RestrictedBaseController{ + private static final Logger LOGGER = FlexLogger.getLogger(ActionPolicyController.class); + + public ActionPolicyController(){ + //Default Constructor + } + + 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 component 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/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java new file mode 100644 index 000000000..820a1ebd9 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java @@ -0,0 +1,119 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.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{ + + private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + AdminTabController.commonClassDao = commonClassDao; + } + + @Autowired + private AdminTabController(CommonClassDao commonClassDao){ + AdminTabController.commonClassDao = commonClassDao; + } + + public AdminTabController() { + //default constructor + } + + @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){ + LOGGER.error("Exception Occured"+e); + } + } + + @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){ + LOGGER.error("Exception Occured"+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/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java new file mode 100644 index 000000000..f78a79c9c --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java @@ -0,0 +1,377 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.model.PDPGroupContainer; +import org.onap.policy.model.PDPPolicyContainer; +import org.onap.policy.model.Roles; +import org.onap.policy.rest.adapter.AutoPushTabAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +import org.onap.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 PDPPolicyContainer policyContainer; + + private PolicyController policyController; + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + private List data; + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + PolicyController controller = getPolicyControllerInstance(); + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + message); + } + + } + } + + private PolicyController getPolicyControllerInstance(){ + return policyController != null ? getPolicyController() : new PolicyController(); + } + + @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 = new ArrayList(); + String userId = UserUtils.getUserSession(request).getOrgUserId(); + Map model = new HashMap<>(); + ObjectMapper mapper = new ObjectMapper(); + PolicyController controller = policyController != null ? getPolicyController() : new PolicyController(); + List userRoles = controller.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{ + if(!userRole.getScope().equals("")){ + scopes.add(userRole.getScope()); + } + } + } + } + if (roles.contains("super-admin") || roles.contains("super-editor") || roles.contains("super-guest")) { + data = commonClassDao.getData(PolicyVersion.class); + }else{ + if(!scopes.isEmpty()){ + for(String scope : scopes){ + String query = "From PolicyVersion where policy_name like '"+scope+"%' and id > 0"; + List filterdatas = commonClassDao.getDataByQuery(query); + if(filterdatas != null){ + for(int i =0; i < filterdatas.size(); i++){ + data.add(filterdatas.get(i)); + } + } + } + }else{ + PolicyVersion emptyPolicyName = new PolicyVersion(); + emptyPolicyName.setPolicyName("Please Contact Policy Super Admin, There are no scopes assigned to you"); + data.add(emptyPolicyName); + } + } + 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){ + logger.error("Exception Occured"+e); + } + } + + @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<>(); + PolicyController controller = getPolicyControllerInstance(); + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + ObjectMapper mapper = new ObjectMapper(); + this.container = new PDPGroupContainer(controller.getPapEngine()); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + AutoPushTabAdapter adapter = mapper.readValue(root.get("pushTabData").toString(), AutoPushTabAdapter.class); + for (Object pdpGroupId : adapter.getPdpDatas()) { + LinkedHashMap selectedPDP = (LinkedHashMap)pdpGroupId; + for(OnapPDPGroup 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_"); + } + String[] split = dbCheckName.split(":"); + String query = "FROM PolicyEntity where policyName = '"+split[1]+"' and scope ='"+split[0]+"'"; + 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()); + } + StdPDPGroup selectedGroup = (StdPDPGroup) pdpDestinationGroupId; + if (selectedPolicy != null) { + // Add Current policies from container + for (OnapPDPGroup group : container.getGroups()) { + if (group.getId().equals(selectedGroup.getId())) { + currentPoliciesInGroup.addAll(group.getPolicies()); + } + } + // copy policy to PAP + try { + controller.getPapEngine().copyPolicy(selectedPolicy, (StdPDPGroup) pdpDestinationGroupId); + } catch (PAPException e) { + logger.error("Exception Occured"+e); + 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.setOnapPdps(pdpGroup.getOnapPdps()); + 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 { + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.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(); + this.policyContainer.removeItem(data); + } + Set changedPolicies = new HashSet<>(); + changedPolicies.addAll((Collection) this.policyContainer.getItemIds()); + StdPDPGroup updatedGroupObject = new StdPDPGroup(group.getId(), group.isDefaultGroup(), group.getName(), group.getDescription(),null); + updatedGroupObject.setPolicies(changedPolicies); + updatedGroupObject.setOnapPdps(group.getOnapPdps()); + 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/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java new file mode 100644 index 000000000..3107950c9 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java @@ -0,0 +1,551 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.controller; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.PrintWriter; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.BRMSParamTemplate; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.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 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.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 CreateBRMSParamController extends RestrictedBaseController { + private static final Logger policyLogger = FlexLogger.getLogger(CreateBRMSParamController.class); + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + CreateBRMSParamController.commonClassDao = commonClassDao; + } + + @Autowired + private CreateBRMSParamController(CommonClassDao commonClassDao){ + CreateBRMSParamController.commonClassDao = commonClassDao; + } + + public CreateBRMSParamController(){} + protected PolicyRestAdapter policyAdapter = null; + + private HashMap dynamicLayoutMap; + + private static String brmsTemplateVlaue = "<$%BRMSParamTemplate="; + private static String string = "String"; + + + @RequestMapping(value={"/policyController/getBRMSTemplateData.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void getBRMSParamPolicyRuleData(HttpServletRequest request, HttpServletResponse response){ + try{ + 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(PolicyController.getPolicydata()).toString().replaceAll("^\"|\"$", "")); + generateUI(rule); + response.setCharacterEncoding(PolicyController.getCharacterencoding()); + response.setContentType(PolicyController.getContenttype()); + request.setCharacterEncoding(PolicyController.getCharacterencoding()); + + PrintWriter out = response.getWriter(); + String responseString = mapper.writeValueAsString(dynamicLayoutMap); + JSONObject j = new JSONObject("{policyData: " + responseString + "}"); + out.write(j.toString()); + }catch(Exception e){ + policyLogger.error("Exception Occured while getting BRMS Rule data" , e); + } + } + + protected String findRule(String ruleTemplate) { + List datas = commonClassDao.getDataById(BRMSParamTemplate.class, "ruleName", ruleTemplate); + if(datas != null && !datas.isEmpty()){ + BRMSParamTemplate bRMSParamTemplate = (BRMSParamTemplate) datas.get(0); + return bRMSParamTemplate.getRule(); + } + return null; + } + + protected void generateUI(String rule) { + if(rule!=null){ + try { + StringBuilder params = new StringBuilder(""); + 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) { + policyLogger.info("Just for Logging"+e); + line = line.split("\\/\\*")[0]; + } + } else { + line = line.split("\\/\\*")[0]; + } + } + if (line.contains("*/")) { + comment = false; + try { + line = line.split("\\*\\/")[1].replace("*/", ""); + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + line = ""; + } + } + if (comment) { + continue; + } + if (flag) { + params.append(line); + } + if (line.contains("declare Params")) { + params.append(line); + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = new StringBuilder(params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", "")); + String[] components = params.toString().split(":"); + String caption = ""; + for (int i = 0; i < components.length; i++) { + String type = ""; + if (i == 0) { + caption = components[i]; + } + if("".equals(caption)){ + break; + } + String nextComponent = ""; + try { + nextComponent = components[i + 1]; + } catch (Exception e) { + policyLogger.info("Just for Logging"+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) { + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + } + } + + private void createField(String caption, String type) { + dynamicLayoutMap.put(caption, type); + } + + /* + * When the User Click Edit or View Policy the following method will get invoked for setting the data to PolicyRestAdapter. + * Which is used to bind the data in GUI + */ + public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + 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 (policyLogger.isDebugEnabled()) { + policyLogger.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){ + policyLogger.info("Just for Logging"+e); + description = policy.getDescription(); + } + policyAdapter.setPolicyDescription(description); + setDataAdapterFromAdviceExpressions(policy, policyAdapter); + 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)); + } + policyAdapter.setRuleData(drlRule); + } + TargetType target = policy.getTarget(); + if (target != null) { + setDataToAdapterFromTarget(target, policyAdapter); + } + } + } + + private void setDataAdapterFromAdviceExpressions(PolicyType policy, PolicyRestAdapter policyAdapter){ + ArrayList attributeList = new ArrayList<>(); + // 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); + @SuppressWarnings("unchecked") + 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); + } + } + + private void setDataToAdapterFromTarget(TargetType target, PolicyRestAdapter policyAdapter){ + // 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) { + setDataToAdapterFromMatchList(matchList, policyAdapter); + } + } + } + } + } + } + + private void setDataToAdapterFromMatchList(List matchList, PolicyRestAdapter policyAdapter){ + 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); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + + if ("RiskType".equals(attributeId)){ + policyAdapter.setRiskType(value); + } + if ("RiskLevel".equals(attributeId)){ + policyAdapter.setRiskLevel(value); + } + if ("guard".equals(attributeId)){ + policyAdapter.setGuard(value); + } + if ("TTLDate".equals(attributeId) && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + } + + 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 + public void paramUIGenerate(PolicyRestAdapter policyAdapter, PolicyEntity entity) { + String data = entity.getConfigurationData().getConfigBody(); + if(data != null){ + File file = new File(PolicyController.getConfigHome() +File.separator+ entity.getConfigurationData().getConfigurationName()); + if(file.exists()){ + try (BufferedReader br = new BufferedReader(new FileReader(file))) { + StringBuilder sb = new StringBuilder(); + String line = br.readLine(); + while (line != null) { + sb.append(line); + sb.append("\n"); + line = br.readLine(); + } + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+ e.getMessage() + e); + } + } + try { + StringBuilder params = new StringBuilder(""); + Boolean flag = false; + Boolean comment = false; + for (String line : Files.readAllLines(Paths.get(file.toString()))) { + if (line.isEmpty() || line.startsWith("//")) { + continue; + } + if(line.contains(brmsTemplateVlaue)){ + String value = line.substring(line.indexOf("<$%"),line.indexOf("%$>")); + value = value.replace(brmsTemplateVlaue, ""); + policyAdapter.setRuleName(value); + } + if (line.startsWith("/*")) { + comment = true; + continue; + } + if ((line.contains("//"))&&(!(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) { + policyLogger.info("Just for Logging"+e); + line = line.split("\\/\\*")[0]; + } + } else { + line = line.split("\\/\\*")[0]; + } + } + if (line.contains("*/")) { + comment = false; + try { + line = line.split("\\*\\/")[1] + .replace("*/", ""); + } catch (Exception e) { + policyLogger.info("Just for Logging"+e); + line = ""; + } + } + if (comment) { + continue; + } + if (flag) { + params.append(line); + } + if (line.contains("rule") && line.contains(".Params\"")) { + params.append(line); + flag = true; + } + if (line.contains("end") && flag) { + break; + } + } + params = new StringBuilder(params.substring(params.indexOf(".Params\"")+ 8)); + params = new StringBuilder(params.toString().replaceAll("\\s+", "").replace("salience1000whenthenParamsparams=newParams();","") + .replace("insert(params);end", "") + .replace("params.set", "")); + String[] components = params.toString().split("\\);"); + if(components!= null && components.length > 0){ + for (int i = 0; i < components.length; i++) { + String value = null; + components[i] = components[i]+")"; + 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) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + e.getMessage() + e); + } + } + + } + + // set View Rule + @SuppressWarnings("unchecked") + @RequestMapping(value={"/policyController/ViewBRMSParamPolicyRule.htm"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void setViewRule(HttpServletRequest request, HttpServletResponse response){ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyRestAdapter policyData = mapper.readValue(root.get(PolicyController.getPolicydata()).get("policy").toString(), PolicyRestAdapter.class); + policyData.setDomainDir(root.get(PolicyController.getPolicydata()).get("model").get("name").toString().replace("\"", "")); + if(root.get(PolicyController.getPolicydata()).get("model").get("type").toString().replace("\"", "").equals(PolicyController.getFile())){ + policyData.setEditPolicy(true); + } + + String body = ""; + + body = "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI purpose. \n\t " + + brmsTemplateVlaue + policyData.getRuleName() + "%$> \n */ \n"; + body = body + findRule((String) policyData.getRuleName()) + "\n"; + StringBuilder generatedRule = new StringBuilder(); + generatedRule.append("rule \""+ policyData.getDomainDir().replace("\\", ".") +".Config_BRMS_Param_" + policyData.getPolicyName()+".Params\" \n\tsalience 1000 \n\twhen\n\tthen\n\t\tParams params = new Params();"); + + if(policyData.getRuleData().size() > 0){ + for(Object keyValue: policyData.getRuleData().keySet()){ + String key = keyValue.toString().substring(0, 1).toUpperCase() + keyValue.toString().substring(1); + if (string.equals(keyValue)) { + generatedRule.append("\n\t\tparams.set" + + key + "(\"" + + policyData.getRuleData().get(keyValue).toString() + "\");"); + } else { + generatedRule.append("\n\t\tparams.set" + + key + "(" + + policyData.getRuleData().get(keyValue).toString() + ");"); + } + } + } + generatedRule.append("\n\t\tinsert(params);\nend"); + policyLogger.info("New rule generated with :" + generatedRule.toString()); + body = body + generatedRule.toString(); + // 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()); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java new file mode 100644 index 000000000..9851d3165 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.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; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.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){ + logger.info("Not able to see the createdby in description. So, add generic description", 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(); + 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); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + } + } + } + } + } + } + } + } + + 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/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java new file mode 100644 index 000000000..a7ce45ec4 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java @@ -0,0 +1,709 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.ClosedLoopFaultBody; +import org.onap.policy.rest.adapter.ClosedLoopFaultTriggerUISignatures; +import org.onap.policy.rest.adapter.ClosedLoopSignatures; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.OnapName; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.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.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.TargetType; + +@Controller +@RequestMapping("/") +public class CreateClosedLoopFaultController extends RestrictedBaseController{ + + private static final Logger policyLogger = FlexLogger.getLogger(CreateClosedLoopFaultController.class); + + 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){ + try{ + 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); + + }catch(Exception e){ + policyLogger.error("Exception Occured while setting data to Adapter" , e); + } + 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){ + policyLogger.info("General error" , 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){ + policyLogger.info("General error" , e); + } + try{ + String operatorBox = connectTraps.get("operatorBox"); + resultBody = resultBody + operatorBox +"("; + }catch (NullPointerException e){ + policyLogger.info("General error" , 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){ + policyLogger.info("General error" , e); + } + try{ + String trapCount2 = connectTraps.get("trapCount2"); + resultBody = resultBody + ", Time = " + trapCount2 + ")"; + }catch(NullPointerException e){ + policyLogger.info("General error" , 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(); + 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); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + + // First match in the target is OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + OnapName onapName = new OnapName(); + onapName.setOnapName(value); + policyAdapter.setOnapNameField(onapName); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + } + } + } + } + } + } + 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) { + policyLogger.error("Exception Occured"+e); + } + + 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/onap/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java new file mode 100644 index 000000000..a4d6014c9 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.admin.PolicyManagerServlet; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.ClosedLoopPMBody; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.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.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.TargetType; + +public class CreateClosedLoopPMController{ + + private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPMController.class); + + 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){ + LOGGER.info("General error" , 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) { + Iterator iterMatch = matchList.iterator(); + while (matchList.size()>1 && 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); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + + // First match in the target is OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + if (attributeId.equals("ServiceType")){ + 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); + } + } + } + } + } + } + } + } + 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) { + LOGGER.error("Exception Occured"+e); + } + } + + //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/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java new file mode 100644 index 000000000..609a45c20 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java @@ -0,0 +1,1622 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.controller; + + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +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.Arrays; +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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.GroupPolicyScopeList; +import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.util.MSAttributeObject; +import org.onap.policy.rest.util.MSModelUtils; +import org.onap.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 org.yaml.snakeyaml.Yaml; + +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.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.TargetType; + +@Controller +@RequestMapping("/") +public class CreateDcaeMicroServiceController extends RestrictedBaseController { + private static final Logger LOGGER = FlexLogger.getLogger(CreateDcaeMicroServiceController.class); + + private static CommonClassDao commonClassDao; + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + CreateDcaeMicroServiceController.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<>(); + //Tosca Model related Datastructure. + String referenceAttributes; + String attributeString; + String listConstraints; + String subAttributeString; + HashMap retmap = new HashMap<>(); + Set uniqueKeys= new HashSet<>(); + Set uniqueDataKeys= new HashSet<>(); + StringBuilder dataListBuffer=new StringBuilder(); + List dataConstraints= new ArrayList <>(); + + public static final String DATATYPE = "data_types.policy.data."; + public static final String PROPERTIES=".properties."; + public static final String TYPE=".type"; + public static final String STRING="string"; + public static final String INTEGER="integer"; + public static final String LIST="list"; + public static final String DEFAULT=".default"; + public static final String REQUIRED=".required"; + public static final String MANYFALSE=":MANY-false"; + + + @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", e); + } + + 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", e); + } + LOGGER.info(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",e); + } + return cleanJson; + } + + // Second index of dot should be returned. + public int stringBetweenDots(String str){ + String stringToSearch=str; + String[]ss=stringToSearch.split("\\."); + if(ss!=null){ + int len= ss.length; + if(len>2){ + uniqueKeys.add(ss[2]); + } + } + + return uniqueKeys.size(); + } + + public void stringBetweenDotsForDataFields(String str){ + String stringToSearch=str; + String[]ss=stringToSearch.split("\\."); + if(ss!=null){ + int len= ss.length; + + if(len>2){ + uniqueDataKeys.add(ss[0]+"%"+ss[2]); + } + } + } + + + public Map load(String fileName) throws IOException { + File newConfiguration = new File(fileName); + InputStream is = null; + try { + is = new FileInputStream(newConfiguration); + } catch (FileNotFoundException e) { + LOGGER.error(e); + } + + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map yamlMap = (Map) yaml.load(is); + StringBuilder sb = new StringBuilder(); + Map settings = new HashMap<>(); + if (yamlMap == null) { + return settings; + } + List path = new ArrayList <>(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + public Map load(byte[] source) throws IOException { + Yaml yaml = new Yaml(); + @SuppressWarnings("unchecked") + Map yamlMap = (Map) yaml.load(Arrays.toString(source)); + StringBuilder sb = new StringBuilder(); + Map settings = new HashMap <>(); + if (yamlMap == null) { + return settings; + } + List path = new ArrayList <>(); + serializeMap(settings, sb, path, yamlMap); + return settings; + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private void serializeMap(Map settings, StringBuilder sb, List path, Map yamlMap) { + for (Map.Entry entry : yamlMap.entrySet()) { + if (entry.getValue() instanceof Map) { + path.add((String) entry.getKey()); + serializeMap(settings, sb, path, (Map) entry.getValue()); + path.remove(path.size() - 1); + } else if (entry.getValue() instanceof List) { + path.add((String) entry.getKey()); + serializeList(settings, sb, path, (List) entry.getValue()); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, (String) entry.getKey(), entry.getValue()); + } + } + } + + @SuppressWarnings("unchecked") + private void serializeList(Map settings, StringBuilder sb, List path, List yamlList) { + int counter = 0; + for (Object listEle : yamlList) { + if (listEle instanceof Map) { + path.add(Integer.toString(counter)); + serializeMap(settings, sb, path, (Map) listEle); + path.remove(path.size() - 1); + } else if (listEle instanceof List) { + path.add(Integer.toString(counter)); + serializeList(settings, sb, path, (List) listEle); + path.remove(path.size() - 1); + } else { + serializeValue(settings, sb, path, Integer.toString(counter), listEle); + } + counter++; + } + } + + private void serializeValue(Map settings, StringBuilder sb, List path, String name, Object value) { + if (value == null) { + return; + } + sb.setLength(0); + for (String pathEle : path) { + sb.append(pathEle).append('.'); + } + sb.append(name); + settings.put(sb.toString(), value.toString()); + } + + void parseDataAndPolicyNodes(Map map){ + for(String key:map.keySet()){ + if(key.contains("policy.nodes.Root")) + { + continue; + } + else if(key.contains("policy.nodes")){ + String wordToFind = "policy.nodes."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+13, key.length()); + + stringBetweenDots(subNodeString); + } + else if(key.contains("policy.data")){ + String wordToFind="policy.data."; + int indexForPolicyNode=key.indexOf(wordToFind); + String subNodeString= key.substring(indexForPolicyNode+12, key.length()); + + stringBetweenDotsForDataFields(subNodeString); + } + } + } + + HashMap parseDataNodes(Map map){ + HashMap dataMapForJson=new HashMap <>(); + for(String uniqueDataKey: uniqueDataKeys){ + if(uniqueDataKey.contains("%")){ + String[] uniqueDataKeySplit= uniqueDataKey.split("%"); + String findType=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+TYPE; + String typeValue=map.get(findType); + LOGGER.info(typeValue); + if(typeValue.equalsIgnoreCase(STRING)|| + typeValue.equalsIgnoreCase(INTEGER) + ) + { + String findDefault=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+DEFAULT; + String defaultValue= map.get(findDefault); + LOGGER.info("defaultValue is:"+ defaultValue); + + String findRequired=DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+REQUIRED; + String requiredValue= map.get(findRequired); + LOGGER.info("requiredValue is:"+ requiredValue); + + StringBuilder attributeIndividualStringBuilder= new StringBuilder(); + attributeIndividualStringBuilder.append(typeValue+":defaultValue-"); + attributeIndividualStringBuilder.append(defaultValue+":required-"); + attributeIndividualStringBuilder.append(requiredValue+MANYFALSE); + dataMapForJson.put(uniqueDataKey, attributeIndividualStringBuilder.toString()); + } + else if(typeValue.equalsIgnoreCase(LIST)){ + String findList= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.type"; + String listValue=map.get(findList); + if(listValue!=null){ + LOGGER.info("Type of list is:"+ listValue); + //Its userdefined + if(listValue.contains(".")){ + String trimValue=listValue.substring(listValue.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(trimValue+":MANY-true"); + dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); + }//Its string + else{ + StringBuilder stringListItems= new StringBuilder(); + stringListItems.append(uniqueDataKeySplit[1].toUpperCase()+":MANY-false"); + dataMapForJson.put(uniqueDataKey, stringListItems.toString()); + dataListBuffer.append(uniqueDataKeySplit[1].toUpperCase()+"=["); + for(int i=0;i<10;i++){ + String findConstraints= DATATYPE+uniqueDataKeySplit[0]+PROPERTIES+uniqueDataKeySplit[1]+".entry_schema.constraints.0.valid_values."+i; + String constraintsValue=map.get(findConstraints); + LOGGER.info(constraintsValue); + if(constraintsValue==null){ + break; + } + else{ + dataConstraints.add(constraintsValue); + dataListBuffer.append(constraintsValue+","); + } + } + dataListBuffer.append("]#"); + + LOGGER.info(dataListBuffer); + } + } + } + else{ + String findUserDefined="data_types.policy.data."+uniqueDataKeySplit[0]+"."+"properties"+"."+uniqueDataKeySplit[1]+".type"; + String userDefinedValue=map.get(findUserDefined); + String trimValue=userDefinedValue.substring(userDefinedValue.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(trimValue+":MANY-false"); + dataMapForJson.put(uniqueDataKey, referenceIndividualStringBuilder.toString()); + + } + } + } + return dataMapForJson; + } + + void constructJsonForDataFields(HashMap dataMapForJson){ + HashMap> dataMapKey= new HashMap <>(); + HashMap hmSub; + for(Map.Entry entry: dataMapForJson.entrySet()){ + String uniqueDataKey= entry.getKey(); + String[] uniqueDataKeySplit=uniqueDataKey.split("%"); + String value= dataMapForJson.get(uniqueDataKey); + if(dataMapKey.containsKey(uniqueDataKeySplit[0])){ + hmSub = dataMapKey.get(uniqueDataKeySplit[0]); + hmSub.put(uniqueDataKeySplit[1], value); + } + else{ + hmSub=new HashMap <>(); + hmSub.put(uniqueDataKeySplit[1], value); + } + + dataMapKey.put(uniqueDataKeySplit[0], hmSub); + } + + JSONObject mainObject= new JSONObject(); + JSONObject json; + for(Map.Entry> entry: dataMapKey.entrySet()){ + String s=entry.getKey(); + json= new JSONObject(); + HashMap jsonHm=dataMapKey.get(s); + for(Map.Entry entryMap:jsonHm.entrySet()){ + String key=entryMap.getKey(); + json.put(key, jsonHm.get(key)); + } + mainObject.put(s,json); + } + Iterator keysItr = mainObject.keys(); + while(keysItr.hasNext()) { + String key = keysItr.next(); + String value = mainObject.get(key).toString(); + retmap.put(key, value); + } + + LOGGER.info("#############################################################################"); + LOGGER.info(mainObject); + LOGGER.info("###############################################################################"); + } + + + HashMap> parsePolicyNodes(Map map){ + HashMap> mapKey= new HashMap <>(); + for(String uniqueKey: uniqueKeys){ + HashMap hm; + + for(Map.Entry entry:map.entrySet()){ + String key=entry.getKey(); + if(key.contains(uniqueKey) && key.contains("policy.nodes")){ + if(mapKey.containsKey(uniqueKey)){ + hm = mapKey.get(uniqueKey); + String keyStr= key.substring(key.lastIndexOf('.')+1); + String valueStr= map.get(key); + if(("type").equals(keyStr)){ + if(!key.contains("entry_schema")) + { + hm.put(keyStr,valueStr); + } + }else{ + hm.put(keyStr,valueStr); + } + + } else { + hm = new HashMap <>(); + String keyStr= key.substring(key.lastIndexOf('.')+1); + String valueStr= map.get(key); + if(("type").equals(keyStr)){ + if(!key.contains("entry_schema")) + { + hm.put(keyStr,valueStr); + } + }else{ + hm.put(keyStr,valueStr); + } + mapKey.put(uniqueKey, hm); + } + } + } + } + return mapKey; + } + + void createAttributes(HashMap> mapKey){ + StringBuilder attributeStringBuilder= new StringBuilder(); + StringBuilder referenceStringBuilder= new StringBuilder(); + StringBuilder listBuffer= new StringBuilder(); + List constraints= new ArrayList<>(); + for(Map.Entry> entry: mapKey.entrySet()){ + String keySetString= entry.getKey(); + HashMap keyValues=mapKey.get(keySetString); + if(keyValues.get("type").equalsIgnoreCase(STRING)|| + keyValues.get("type").equalsIgnoreCase(INTEGER) + ){ + StringBuilder attributeIndividualStringBuilder= new StringBuilder(); + attributeIndividualStringBuilder.append(keySetString+"="); + attributeIndividualStringBuilder.append(keyValues.get("type")+":defaultValue-"); + attributeIndividualStringBuilder.append(keyValues.get("default")+":required-"); + attributeIndividualStringBuilder.append(keyValues.get("required")+":MANY-false"); + attributeStringBuilder.append(attributeIndividualStringBuilder+","); + + } + else if(keyValues.get("type").equalsIgnoreCase(LIST)){ + //List Datatype + Set keys= keyValues.keySet(); + Iterator itr=keys.iterator(); + while(itr.hasNext()){ + String key= itr.next(); + if((!("type").equals(key) ||("required").equals(key))) + { + String value= keyValues.get(key); + //The "." in the value determines if its a string or a user defined type. + if (!value.contains(".")){ + //This is string + constraints.add(keyValues.get(key)); + }else{ + //This is userdefined string + String trimValue=value.substring(value.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-true"); + referenceStringBuilder.append(referenceIndividualStringBuilder+","); + } + } + } + + }else{ + //User defined Datatype. + String value=keyValues.get("type"); + String trimValue=value.substring(value.lastIndexOf('.')+1); + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString+"="+trimValue+":MANY-false"); + referenceStringBuilder.append(referenceIndividualStringBuilder+","); + + } + if(constraints!=null &&constraints.isEmpty()==false){ + //List handling. + listBuffer.append(keySetString.toUpperCase()+"=["); + for(String str:constraints){ + listBuffer.append(str+","); + } + listBuffer.append("]#"); + LOGGER.info(listBuffer); + + + StringBuilder referenceIndividualStringBuilder= new StringBuilder(); + referenceIndividualStringBuilder.append(keySetString+"="+keySetString.toUpperCase()+":MANY-false"); + referenceStringBuilder.append(referenceIndividualStringBuilder+","); + constraints.clear(); + } + } + + dataListBuffer.append(listBuffer); + + + LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + LOGGER.info("Whole attribute String is:"+attributeStringBuilder); + LOGGER.info("Whole reference String is:"+referenceStringBuilder); + LOGGER.info("List String is:"+listBuffer); + LOGGER.info("Data list buffer is:"+dataListBuffer); + LOGGER.info("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$"); + + this.listConstraints=dataListBuffer.toString(); + this.referenceAttributes=referenceStringBuilder.toString(); + this.attributeString=attributeStringBuilder.toString(); + } + + + + public void parseTosca (String fileName){ + Map map= new HashMap<>(); + + try { + map=load(fileName); + + parseDataAndPolicyNodes(map); + + HashMap dataMapForJson=parseDataNodes(map); + + constructJsonForDataFields(dataMapForJson); + + HashMap> mapKey= parsePolicyNodes(map); + + createAttributes(mapKey); + + } catch (IOException e) { + LOGGER.error(e); + } + + } + + 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. + LOGGER.info(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(jsonArray != null && arryKey.equals(nodeKey.substring(0,nodeKey.indexOf("@")))){ + jsonArray.put(decodeContent(node)); + } + if((key.contains("@") && !arryKey.equals(key.substring(0,nodeKey.indexOf("@")))) || !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(jsonArray != null && 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", "rawtypes" }) + 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){ + LOGGER.error(e); + } + } + + 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) { + Iterator iterMatch = matchList.iterator(); + while (matchList.size()>1 && 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); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + // First match in the target is OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + } + if (attributeId.equals("ConfigName")){ + policyAdapter.setConfigName(value); + } + if (attributeId.equals("uuid")){ + policyAdapter.setUuid(value); + } + if (attributeId.equals("location")){ + policyAdapter.setLocation(value); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + readFile(policyAdapter, entity); + } + } + } + } + } + } + } + } + + 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) { + LOGGER.error(e); + } + + } + + @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) { + List groupList= commonClassDao.getDataById(GroupPolicyScopeList.class, "groupList", value); + if(groupList != null && !groupList.isEmpty()){ + GroupPolicyScopeList pScope = (GroupPolicyScopeList) groupList.get(0); + return pScope.getGroupName(); + } + return null; + } + + //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; + boolean yml= false; + for (FileItem item : items) { + if(item.getName().endsWith(".zip") || item.getName().endsWith(".xmi")||item.getName().endsWith(".yml")){ + 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 if(item.getName().endsWith(".yml")){ + this.newModel.setVersion(this.newFile.toString().split("-v")[1].replace(".yml", "")); + yml = 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 if (yml==true){ + parseTosca(this.newFile); + }else { + File file = new File(this.newFile); + fileList.add(file); + } + String modelType= ""; + if(yml==false){ + modelType="xmi"; + //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); + }else{ + modelType="yml"; + modelList.add(this.newModel.getModelName()); + String className=this.newModel.getModelName(); + MSAttributeObject msAttributes= new MSAttributeObject(); + msAttributes.setClassName(className); + + HashMap returnAttributeList =new HashMap<>(); + returnAttributeList.put(className, this.attributeString); + msAttributes.setAttribute(returnAttributeList); + + msAttributes.setSubClass(this.retmap); + + HashMap returnReferenceList =new HashMap<>(); + //String[] referenceArray=this.referenceAttributes.split("="); + returnReferenceList.put(className, this.referenceAttributes); + msAttributes.setRefAttribute(returnReferenceList); + + if(this.listConstraints!=""){ + HashMap enumList =new HashMap<>(); + String[] listArray=this.listConstraints.split("#"); + for(String str:listArray){ + String[] strArr= str.split("="); + if(strArr.length>1){ + enumList.put(strArr[0], strArr[1]); + } + } + msAttributes.setEnumType(enumList); + } + + classMap=new HashMap<>(); + classMap.put(className, msAttributes); + + } + + 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)); + j.put("modelType", modelType); + 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 = null; + 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); + }finally{ + try { + if(zip != null) + zip.close(); + } catch (IOException e) { + LOGGER.error("Exception Occured While closing zipfile " + e); + } + } + } + + private void retreiveDependency(String workingFile, Boolean modelClass) { + + MSModelUtils utils = new MSModelUtils(PolicyController.getMsOnapName(), PolicyController.getMsPolicyName()); + HashMap tempMap = new HashMap<>(); + + tempMap = utils.processEpackage(workingFile, MODEL_TYPE.XMI); + + classMap.putAll(tempMap); + LOGGER.info(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; + } + + public Map getAttributesListRefMap() { + return attributesListRefMap; + } + + public Map> getArrayTextList() { + return arrayTextList; + } + +} + +class DCAEMicroServiceObject { + + private String service; + private String location; + private String uuid; + private String policyName; + private String description; + private String configName; + private String templateVersion; + private String version; + private String priority; + private String policyScope; + private String riskType; + private String riskLevel; + private 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/onap/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java new file mode 100644 index 000000000..828bc3886 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java @@ -0,0 +1,929 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.controller; +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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.AddressGroupJson; +import org.onap.policy.rest.adapter.AddressJson; +import org.onap.policy.rest.adapter.AddressMembers; +import org.onap.policy.rest.adapter.DeployNowJson; +import org.onap.policy.rest.adapter.IdMap; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.adapter.PrefixIPList; +import org.onap.policy.rest.adapter.ServiceGroupJson; +import org.onap.policy.rest.adapter.ServiceListJson; +import org.onap.policy.rest.adapter.ServiceMembers; +import org.onap.policy.rest.adapter.ServicesJson; +import org.onap.policy.rest.adapter.TagDefines; +import org.onap.policy.rest.adapter.Tags; +import org.onap.policy.rest.adapter.Term; +import org.onap.policy.rest.adapter.TermCollector; +import org.onap.policy.rest.adapter.VendorSpecificData; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.AddressGroup; +import org.onap.policy.rest.jpa.FWTagPicker; +import org.onap.policy.rest.jpa.GroupServiceList; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PrefixList; +import org.onap.policy.rest.jpa.SecurityZone; +import org.onap.policy.rest.jpa.ServiceList; +import org.onap.policy.rest.jpa.TermList; +import org.onap.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 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.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.TargetType; + +@Controller +@RequestMapping("/") +public class CreateFirewallController extends RestrictedBaseController { + private static Logger policyLogger = 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().isEmpty()){ + 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) { + 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)) { + String value = prefixList.getPrefixListValue(); + valueDesc.add(value); + String 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 (policyLogger.isDebugEnabled()) { + policyLogger.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){ + policyLogger.info("General error", 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) { + policyLogger.error("Exception Caused while Retriving the JSON body data" +e); + } + + Map termTagMap=null; + if(tc1 != 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) { + 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); + AttributeDesignatorType designator = match.getAttributeDesignator(); + String attributeId = designator.getAttributeId(); + if (attributeId.equals("ConfigName")) { + policyAdapter.setConfigName(value); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + } + } + } + } + } + } + } + } + } + + 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 void setFWViewRule(HttpServletRequest request, HttpServletResponse response){ + 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().isEmpty()){ + 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()); + } catch (Exception e) { + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + 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{ + String networkRole=""; + 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); + + } + networkRole=jpaTagPickerList.getNetworkRole(); + break; + } + } + tags.setTags(tagList); + tags.setTagPickerName(tag); + tags.setRuleName(termCollectorList.get(i)); + tags.setNetworkRole(networkRole); + 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()); + IdMap idMapInstance= new IdMap(); + idMapInstance.setAstraId(jpaSecurityZone.getZoneValue()); + idMapInstance.setVendorId("deviceGroup:dev"); + + List idMap = new ArrayList(); + idMap.add(idMapInstance); + + VendorSpecificData vendorStructure= new VendorSpecificData(); + vendorStructure.setIdMap(idMap); + tc.setVendorSpecificData(vendorStructure); + break; + } + } + + tc.setServiceTypeId("/v0/firewall/pan"); + tc.setConfigName(policyData.getConfigName()); + tc.setVendorServiceId("vipr"); + + 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); + policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "PrefixList value:"+prefixIP); + valueDesc = mapping(prefixIP); + if(!valueDesc.isEmpty()){ + policyLogger.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 (Exception e) { + policyLogger.error("Exception Occured"+e); + } + + }catch (Exception e) { + policyLogger.error("Exception Occured"+e); + } + + return json; + } + +} diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java new file mode 100644 index 000000000..9c07876c1 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.controller; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.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 attribute value 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 OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + } + if (attributeId.equals("RiskType")){ + policyAdapter.setRiskType(value); + } + if (attributeId.equals("RiskLevel")){ + policyAdapter.setRiskLevel(value); + } + if (attributeId.equals("guard")){ + policyAdapter.setGuard(value); + } + if (attributeId.equals("TTLDate") && !value.contains("NA")){ + String newDate = convertDate(value, true); + policyAdapter.setTtlDate(newDate); + } + if (attributeId.equals("ConfigName")){ + policyAdapter.setConfigName(value); + } + // After Onap 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/onap/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java new file mode 100644 index 000000000..d6d4a2c69 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java @@ -0,0 +1,430 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.dao.SystemLogDbDao; +import org.onap.policy.model.PDPGroupContainer; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; + +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 policyLogger = 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; + + private PolicyController policyController; + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + private PolicyController getPolicyControllerInstance(){ + return policyController != null ? getPolicyController() : new PolicyController(); + } + + @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){ + policyLogger.error("Exception Occured"+e); + } + } + + @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){ + policyLogger.error("Exception Occured"+e); + } + } + + @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){ + policyLogger.error("Exception Occured"+e); + } + } + + @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); + PolicyController controller = getPolicyControllerInstance(); + this.pdpConatiner = new PDPGroupContainer(controller.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){ + policyLogger.error("Exception Occured"+e); + } + } + + @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); + PolicyController controller = getPolicyControllerInstance(); + this.pdpConatiner = new PDPGroupContainer(controller.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){ + policyLogger.error("Exception Occured"+e); + } + } + + /* + * Add the PAP information to the PAP Table + */ + public void addPAPToTable(){ + papStatusData = new ArrayList<>(); + String papStatus = null; + try { + PolicyController controller = getPolicyControllerInstance(); + Set groups = controller.getPapEngine().getOnapPDPGroups(); + if (groups == null) { + papStatus = "UNKNOWN"; + throw new PAPException("PAP not running"); + }else { + papStatus = "IS_OK"; + } + } catch (PAPException | NullPointerException e1) { + papStatus = "CANNOT_CONNECT"; + policyLogger.error("Error getting PAP status, PAP not responding to requests", e1); + } + 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 ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0){ + String pdpIpAddress = parseIPSystem(pdp.getId()); + int port = ((OnapPDP) pdp).getJmxPort(); + if (port != 0){ + policyLogger.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) { + + policyLogger.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(); + policyLogger.debug("pdpEvaluationNA value retreived: " + o); + return (long) o; + } catch (MalformedURLException e) { + policyLogger.error("MalformedURLException for JMX connection" , e); + } catch (IOException e) { + policyLogger.error("Error in reteriving" + jmxAttribute + " from JMX connection", e); + } catch (AttributeNotFoundException e) { + policyLogger.error("AttributeNotFoundException " + jmxAttribute + " for JMX connection", e); + } catch (InstanceNotFoundException e) { + policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e); + } catch (MalformedObjectNameException e) { + policyLogger.error("MalformedObjectNameException for JMX connection", e); + } catch (MBeanException e) { + policyLogger.error("MBeanException for JMX connection"); + policyLogger.error("Exception Occured"+e); + } catch (ReflectionException e) { + policyLogger.error("ReflectionException for JMX connection", e); + } + + 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<>(); + 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){ + policyLogger.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID+policy.getName() +e); + } + } + + for (PDP pdp : group.getPdps()){ + // Add rows to the Policy Table + policyList = null; + if ("UP_TO_DATE".equals(pdp.getStatus().getStatus().toString()) && ((OnapPDP) pdp).getJmxPort() != 0){ + String pdpIpAddress = parseIPSystem(pdp.getId()); + policyList = getPolicy(pdpIpAddress, ((OnapPDP) 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(object); + } + } + } + }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(object); + }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(object); + } + } + } + } + } + + /* + * Contact JMX Connector Sever and return the list of {policy id , count} + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private Object getPolicy(String host, int port, String jmxAttribute){ + policyLogger.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(); + policyLogger.debug("policyMap value retreived: " + o); + return o; + } catch (MalformedURLException e) { + policyLogger.error("MalformedURLException for JMX connection" , e); + } catch (IOException e) { + policyLogger.error("AttributeNotFoundException for policyMap" , e); + } catch (AttributeNotFoundException e) { + policyLogger.error("AttributeNotFoundException for JMX connection", e); + } catch (InstanceNotFoundException e) { + policyLogger.error("InstanceNotFoundException " + host + " for JMX connection", e); + } catch (MalformedObjectNameException e) { + policyLogger.error("MalformedObjectNameException for JMX connection", e); + } catch (MBeanException e) { + policyLogger.error("MBeanException for JMX connection", e); + policyLogger.error("Exception Occured"+e); + } catch (ReflectionException e) { + policyLogger.error("ReflectionException for JMX connection", e); + } + + 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/onap/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java new file mode 100644 index 000000000..45369ce2f --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java @@ -0,0 +1,361 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.controller; + +import java.util.ArrayList; +import java.util.Arrays; +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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.adapter.RainyDayParams; +import org.onap.policy.rest.adapter.YAMLParams; +import org.onap.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.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.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 policyLogger = FlexLogger.getLogger(DecisionPolicyController.class); + + public DecisionPolicyController(){} + + protected PolicyRestAdapter policyAdapter = null; + private ArrayList attributeList; + private ArrayList decisionList; + private ArrayList ruleAlgorithmList; + private ArrayList treatmentList = null; + 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<>(); + treatmentList = new ArrayList<>(); + + if (policyAdapter.getPolicyData() instanceof PolicyType) { + RainyDayParams rainydayParams = new RainyDayParams(); + 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){ + policyLogger.info("General error", 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 OnapName, so set that value. + if (attributeId.equals("ONAPName")) { + policyAdapter.setOnapName(value); + } + // Component attributes are saved under Target here we are fetching them back. + // One row is default so we are not adding dynamic component 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); + } + } + } + // Setting rainy day attributes to the parameters object if they exist + boolean rainy = false; + if(!attributeList.isEmpty()) { + for(int i=0; i map = (Map)attributeList.get(i); + if(map.get("key").equals("WorkStep")){ + rainydayParams.setWorkstep(map.get("value")); + rainy=true; + }else if(map.get("key").equals("BB_ID")){ + rainydayParams.setBbid(map.get("value")); + rainy=true; + }else if(map.get("key").equals("ServiceType")){ + rainydayParams.setServiceType(map.get("value")); + rainy=true; + }else if(map.get("key").equals("VNFType")){ + rainydayParams.setVnfType(map.get("value")); + rainy=true; + } + } + } + if(rainy){ + policyAdapter.setRuleProvider("Rainy_Day"); + } + } + + 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.DENY)) { + if(((RuleType) object).getAdviceExpressions()!=null){ + if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("AAF")){ + policyAdapter.setRuleProvider("AAF"); + break; + }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_YAML")){ + policyAdapter.setRuleProvider("GUARD_YAML"); + }else if(((RuleType) object).getAdviceExpressions().getAdviceExpression().get(0).getAdviceId().toString().equalsIgnoreCase("GUARD_BL_YAML")){ + policyAdapter.setRuleProvider("GUARD_BL_YAML"); + } + }else{ + policyAdapter.setRuleProvider("Custom"); + } + ConditionType condition = ((RuleType) object).getCondition(); + if (condition != null) { + ApplyType decisionApply = (ApplyType) condition.getExpression().getValue(); + decisionApply = (ApplyType) decisionApply.getExpression().get(0).getValue(); + ruleAlgoirthmTracker = new LinkedList<>(); + if(policyAdapter.getRuleProvider()!=null && (policyAdapter.getRuleProvider().equals("GUARD_YAML")||(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")))){ + YAMLParams yamlParams = new YAMLParams(); + for(int i=0; i map = (Map)attributeList.get(i); + if(map.get("key").equals("actor")){ + yamlParams.setActor(map.get("value")); + }else if(map.get("key").equals("recipe")){ + yamlParams.setRecipe(map.get("value")); + }else if(map.get("key").equals("targets")){ + yamlParams.setTargets(Arrays.asList(map.get("value").split("\\|"))); + }else if(map.get("key").equals("clname")){ + yamlParams.setClname(map.get("value")); + } + } + ApplyType apply = ((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(0).getValue()); + yamlParams.setGuardActiveStart(((AttributeValueType)apply.getExpression().get(1).getValue()).getContent().get(0).toString()); + yamlParams.setGuardActiveEnd(((AttributeValueType)apply.getExpression().get(2).getValue()).getContent().get(0).toString()); + if(policyAdapter.getRuleProvider().equals("GUARD_BL_YAML")){ + apply = (ApplyType)((ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue()).getExpression().get(2).getValue(); + Iterator> attributes = apply.getExpression().iterator(); + List blackList = new ArrayList<>(); + while(attributes.hasNext()){ + blackList.add(((AttributeValueType)attributes.next().getValue()).getContent().get(0).toString()); + } + yamlParams.setBlackList(blackList); + }else{ + ApplyType timeWindowSection = (ApplyType)((ApplyType)decisionApply.getExpression().get(0).getValue()).getExpression().get(1).getValue(); + yamlParams.setLimit(((AttributeValueType)timeWindowSection.getExpression().get(1).getValue()).getContent().get(0).toString()); + String timeWindow = ((AttributeDesignatorType)((ApplyType)timeWindowSection.getExpression().get(0).getValue()).getExpression().get(0).getValue()).getIssuer(); + yamlParams.setTimeUnits(timeWindow.substring(timeWindow.lastIndexOf(':')+1)); + yamlParams.setTimeWindow(timeWindow.substring(timeWindow.indexOf(":tw:")+4,timeWindow.lastIndexOf(':'))); + } + policyAdapter.setYamlparams(yamlParams); + policyAdapter.setAttributes(new ArrayList()); + policyAdapter.setRuleAlgorithmschoices(new ArrayList()); + break; + } + // Populating Rule Algorithms starting from compound. + prePopulateDecisionCompoundRuleAlgorithm(index, decisionApply); + policyAdapter.setRuleAlgorithmschoices(ruleAlgorithmList); + } + } else if(policyAdapter.getRuleProvider()!=null && policyAdapter.getRuleProvider().equals("Rainy_Day")&& ((RuleType) object).getEffect().equals(EffectType.PERMIT)) { + + TargetType ruleTarget = ((RuleType) object).getTarget(); + AdviceExpressionsType adviceExpression = ((RuleType) object).getAdviceExpressions(); + + String errorcode = ruleTarget.getAnyOf().get(0).getAllOf().get(0).getMatch(). + get(1).getAttributeValue().getContent().get(0).toString(); + JAXBElement tempTreatmentObj = (JAXBElement) adviceExpression.getAdviceExpression(). + get(0).getAttributeAssignmentExpression().get(0).getExpression(); + String treatment = tempTreatmentObj.getValue().getContent().get(0).toString(); + + prePopulateRainyDayTreatments(errorcode, treatment); + + } + } + } + } + + rainydayParams.setTreatmentTableChoices(treatmentList); + policyAdapter.setRainyday(rainydayParams); + policyAdapter.setSettings(decisionList); + } + + } + + private void prePopulateRainyDayTreatments(String errorcode, String treatment) { + Map ruleMap = new HashMap<>(); + + ruleMap.put("errorcode", errorcode); + ruleMap.put("treatment", treatment); + treatmentList.add(ruleMap); + + } + + 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 (policyLogger.isDebugEnabled()) { + policyLogger.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 (policyLogger.isDebugEnabled()) { + policyLogger.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); + break; + } + } + + 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/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java new file mode 100644 index 000000000..0f8a3c988 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java @@ -0,0 +1,394 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.controller; + + +import java.io.File; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.model.PDPGroupContainer; +import org.onap.policy.model.Roles; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.policy.xacml.std.pap.StdPDP; +import org.onap.policy.xacml.std.pap.StdPDPGroup; +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.http.MediaType; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; + +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 PDPController extends RestrictedBaseController { + private static final Logger policyLogger = FlexLogger.getLogger(PDPController.class); + + protected List groups = Collections.synchronizedList(new ArrayList()); + private PDPGroupContainer container; + + private static String SUPERADMIN = "super-admin"; + private static String SUPEREDITOR = "super-editor"; + private static String SUPERGUEST = "super-guest"; + + private Set groupsData; + + private boolean junit = false; + + private PolicyController policyController; + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + public synchronized void refreshGroups(HttpServletRequest request) { + synchronized(this.groups) { + this.groups.clear(); + try { + PolicyController controller = getPolicyControllerInstance(); + Set filteredPolicies = new HashSet<>(); + Set scopes = null; + List roles = null; + String userId = isJunit() ? "Test" : UserUtils.getUserSession(request).getOrgUserId(); + List userRoles = controller.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(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST) ) { + if(!junit){ + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + }else{ + this.groups.addAll(this.getGroupsData()); + } + }else{ + if(!userRoles.isEmpty()){ + if(!scopes.isEmpty()){ + this.groups.addAll(controller.getPapEngine().getOnapPDPGroups()); + List tempGroups = new ArrayList<>(); + if(!groups.isEmpty()){ + Iterator pdpGroup = groups.iterator(); + while(pdpGroup.hasNext()){ + OnapPDPGroup group = pdpGroup.next(); + Set policies = group.getPolicies(); + for(PDPPolicy policy : policies){ + for(String scope : scopes){ + scope = scope.replace(File.separator, "."); + String policyName = policy.getId(); + if(policyName.contains(".Config_")){ + policyName = policyName.substring(0, policyName.lastIndexOf(".Config_")); + }else if(policyName.contains(".Action_")){ + policyName = policyName.substring(0, policyName.lastIndexOf(".Action_")); + }else if(policyName.contains(".Decision_")){ + policyName = policyName.substring(0, policyName.lastIndexOf(".Decision_")); + } + if(policyName.startsWith(scope)){ + filteredPolicies.add(policy); + } + } + } + pdpGroup.remove(); + StdPDPGroup newGroup = (StdPDPGroup) group; + newGroup.setPolicies(filteredPolicies); + tempGroups.add(newGroup); + } + groups.clear(); + groups = tempGroups; + } + } + } + } + } catch (PAPException e) { + String message = "Unable to retrieve Groups from server: " + e; + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Pap Engine is Null" + message); + } + } + } + + @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(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + response.getWriter().write(j.toString()); + } + catch (Exception e){ + policyLogger.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 void savePDPGroup(HttpServletRequest request, HttpServletResponse response){ + try { + ObjectMapper mapper = new ObjectMapper(); + PolicyController controller = getPolicyControllerInstance(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + this.container = new PDPGroupContainer(controller.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(); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while creating the PDP Group" + message + e); + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } + catch (Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e); + response.setCharacterEncoding("UTF-8"); + PrintWriter out = null; + try { + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Saving the PDP Group" + e1); + } + } + } + + @RequestMapping(value={"/pdp_Group/remove_pdp_group"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void removePDPGroup(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.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(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } + catch (Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing the PDP Group" + e); + PrintWriter out; + try { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured"+ e1); + } + } + } + + @RequestMapping(value={"/pdp_Group/save_pdpTogroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response){ + try { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.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(); + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + message + e); + } + + + response.setCharacterEncoding("UTF-8"); + response.setContentType("application / json"); + request.setCharacterEncoding("UTF-8"); + + PrintWriter out = response.getWriter(); + refreshGroups(request); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(groups)); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + } + catch (Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Creating Pdp in PDP Group" + e); + PrintWriter out; + try { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured"+ e1); + } + } + } + + @RequestMapping(value={"/pdp_Group/remove_pdpFromGroup"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) + public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response){ + try{ + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + JsonNode root = mapper.readTree(request.getReader()); + PolicyController controller = getPolicyControllerInstance(); + this.container = new PDPGroupContainer(controller.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(request); + String responseString = mapper.writeValueAsString(groups); + JSONObject j = new JSONObject("{pdpEntityDatas: " + responseString + "}"); + out.write(j.toString()); + } + catch (Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Removing Pdp from PDP Group" + e); + PrintWriter out; + try { + response.setCharacterEncoding("UTF-8"); + request.setCharacterEncoding("UTF-8"); + out = response.getWriter(); + out.write(e.getMessage()); + } catch (Exception e1) { + policyLogger.error("Exception Occured"+ e1); + } + } + } + + private PolicyController getPolicyControllerInstance(){ + return policyController != null ? getPolicyController() : new PolicyController(); + } + + public boolean isJunit() { + return junit; + } + + public void setJunit(boolean junit) { + this.junit = junit; + } + + public Set getGroupsData() { + return groupsData; + } + + public void setGroupsData(Set groupsData) { + this.groupsData = groupsData; + } +} + +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/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java new file mode 100644 index 000000000..aa1918967 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java @@ -0,0 +1,696 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.admin.PolicyNotificationMail; +import org.onap.policy.admin.RESTfulPAPEngine; +import org.onap.policy.model.PDPGroupContainer; +import org.onap.policy.model.Roles; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.XacmlAdminAuthorization; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.Datatype; +import org.onap.policy.rest.jpa.FunctionDefinition; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.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.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.PAPPolicyEngine; + +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; + + +@Controller +@RequestMapping("/") +public class PolicyController extends RestrictedBaseController { + private static final Logger policyLogger = FlexLogger.getLogger(PolicyController.class); + + private static CommonClassDao commonClassDao; + + // Our authorization object + // + XacmlAdminAuthorization authorizer = new XacmlAdminAuthorization(); + // + // The PAP Engine + // + private static PAPPolicyEngine papEngine; + + private static String logTableLimit; + private 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; + + //Constant variables used across Policy-sdk + private static final String policyData = "policyData"; + private static final String characterEncoding = "UTF-8"; + private static final String contentType = "application/json"; + private static final String file = "file"; + + //Smtp Java Mail Properties + private static String smtpHost = null; + private static String smtpPort = null; + private static String smtpUsername = null; + private static String smtpPassword = null; + private static String smtpApplicationName = null; + private static String smtpEmailExtension = null; + //log db Properties + private static String logdbDriver = null; + private static String logdbUrl = null; + private static String logdbUserName = null; + private static String logdbPassword = null; + private static String logdbDialect = null; + //Xacml db properties + private static String xacmldbUrl = null; + private static String xacmldbUserName = null; + private static String xacmldbPassword = null; + + //AutoPush feature. + private static String autoPushAvailable; + private static String autoPushDSClosedLoop; + private static String autoPushDSFirewall; + private static String autoPushDSMicroservice; + private static String autoPushPDPGroup; + + //papURL + private static String papUrl; + + //MicroService Model Properties + private static String msOnapName; + private static String msPolicyName; + + //WebApp directories + private static String configHome; + private static String actionHome; + + @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 + setPapUrl(prop.getProperty("xacml.rest.pap.url")); + // get the property values + setSmtpHost(prop.getProperty("onap.smtp.host")); + setSmtpPort(prop.getProperty("onap.smtp.port")); + setSmtpUsername(prop.getProperty("onap.smtp.userName")); + setSmtpPassword(prop.getProperty("onap.smtp.password")); + setSmtpApplicationName(prop.getProperty("onap.application.name")); + setSmtpEmailExtension(prop.getProperty("onap.smtp.emailExtension")); + //Log Database Properties + setLogdbDriver(prop.getProperty("xacml.log.db.driver")); + setLogdbUrl(prop.getProperty("xacml.log.db.url")); + setLogdbUserName(prop.getProperty("xacml.log.db.user")); + setLogdbPassword(prop.getProperty("xacml.log.db.password")); + setLogdbDialect(prop.getProperty("onap.dialect")); + //Xacml Database Properties + setXacmldbUrl(prop.getProperty("javax.persistence.jdbc.url")); + setXacmldbUserName(prop.getProperty("javax.persistence.jdbc.user")); + setXacmldbPassword(prop.getProperty("javax.persistence.jdbc.password")); + //AutoPuh + setAutoPushAvailable(prop.getProperty("xacml.automatic.push")); + setAutoPushDSClosedLoop(prop.getProperty("xacml.autopush.closedloop")); + setAutoPushDSFirewall(prop.getProperty("xacml.autopush.firewall")); + setAutoPushDSMicroservice(prop.getProperty("xacml.autopush.microservice")); + setAutoPushPDPGroup(prop.getProperty("xacml.autopush.pdpGroup")); + //Micro Service Properties + setMsOnapName(prop.getProperty("xacml.policy.msOnapName")); + setMsPolicyName(prop.getProperty("xacml.policy.msPolicyName")); + //WebApp directories + setConfigHome(prop.getProperty("xacml.rest.config.webapps") + "Config"); + setActionHome(prop.getProperty("xacml.rest.config.webapps") + "Action"); + //Get the Property Values for Dashboard tab Limit + try{ + setLogTableLimit(prop.getProperty("xacml.onap.dashboard.logTableLimit")); + setSystemAlertTableLimit(prop.getProperty("xacml.onap.dashboard.systemAlertTableLimit")); + }catch(Exception e){ + policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Dashboard tab Property fields are missing" +e); + setLogTableLimit("5000"); + setSystemAlertTableLimit("2000"); + } + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "xacml.admin.properties"); + } catch (IOException ex) { + policyLogger.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) { + policyLogger.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 = 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())) { + 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){ + policyLogger.error(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); + return (PolicyEntity) data.get(0); + } + + public static Map getUserRoles(String userId) { + Map scopes = new HashMap<>(); + List roles = commonClassDao.getDataById(Roles.class, "loginId", userId); + if (roles != null && !roles.isEmpty()) { + for (Object role : roles) { + scopes.put(((Roles) role).getScope(), (Roles) role); + } + } + return scopes; + } + + public 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 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){ + policyLogger.error("Exception Occured"+e); + } + } + + //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) { + policyLogger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR+"Exception Occured while loading PAP"+e); + } + Map model = new HashMap<>(); + return new ModelAndView("policy_Editor","model", model); + } + + public 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 List getData(@SuppressWarnings("rawtypes") Class className){ + return commonClassDao.getData(className); + } + + public PolicyVersion getPolicyEntityFromPolicyVersion(String query){ + return (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", query); + } + + 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) { + policyLogger.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; + } + + public static String getLogTableLimit() { + return logTableLimit; + } + + public static void setLogTableLimit(String logTableLimit) { + PolicyController.logTableLimit = logTableLimit; + } + + public static String getSystemAlertTableLimit() { + return systemAlertTableLimit; + } + + public static void setSystemAlertTableLimit(String systemAlertTableLimit) { + PolicyController.systemAlertTableLimit = systemAlertTableLimit; + } + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + PolicyController.commonClassDao = commonClassDao; + } + + public XacmlAdminAuthorization getAuthorizer() { + return authorizer; + } + + public void setAuthorizer(XacmlAdminAuthorization authorizer) { + this.authorizer = authorizer; + } + + public static Map> getMapDatatype2Function() { + return mapDatatype2Function; + } + + public static void setMapDatatype2Function(Map> mapDatatype2Function) { + PolicyController.mapDatatype2Function = mapDatatype2Function; + } + + public static Map getMapID2Function() { + return mapID2Function; + } + + public static void setMapID2Function(Map mapID2Function) { + PolicyController.mapID2Function = mapID2Function; + } + + public static String getSmtpHost() { + return smtpHost; + } + + public static void setSmtpHost(String smtpHost) { + PolicyController.smtpHost = smtpHost; + } + + public static String getSmtpPort() { + return smtpPort; + } + + public static void setSmtpPort(String smtpPort) { + PolicyController.smtpPort = smtpPort; + } + + public static String getSmtpUsername() { + return smtpUsername; + } + + public static void setSmtpUsername(String smtpUsername) { + PolicyController.smtpUsername = smtpUsername; + } + + public static String getSmtpPassword() { + return smtpPassword; + } + + public static void setSmtpPassword(String smtpPassword) { + PolicyController.smtpPassword = smtpPassword; + } + + public static String getSmtpApplicationName() { + return smtpApplicationName; + } + + public static void setSmtpApplicationName(String smtpApplicationName) { + PolicyController.smtpApplicationName = smtpApplicationName; + } + + public static String getSmtpEmailExtension() { + return smtpEmailExtension; + } + + public static void setSmtpEmailExtension(String smtpEmailExtension) { + PolicyController.smtpEmailExtension = smtpEmailExtension; + } + + public static String getLogdbDriver() { + return logdbDriver; + } + + public static void setLogdbDriver(String logdbDriver) { + PolicyController.logdbDriver = logdbDriver; + } + + public static String getLogdbUrl() { + return logdbUrl; + } + + public static void setLogdbUrl(String logdbUrl) { + PolicyController.logdbUrl = logdbUrl; + } + + public static String getLogdbUserName() { + return logdbUserName; + } + + public static void setLogdbUserName(String logdbUserName) { + PolicyController.logdbUserName = logdbUserName; + } + + public static String getLogdbPassword() { + return logdbPassword; + } + + public static void setLogdbPassword(String logdbPassword) { + PolicyController.logdbPassword = logdbPassword; + } + + public static String getLogdbDialect() { + return logdbDialect; + } + + public static void setLogdbDialect(String logdbDialect) { + PolicyController.logdbDialect = logdbDialect; + } + + public static String getXacmldbUrl() { + return xacmldbUrl; + } + + public static void setXacmldbUrl(String xacmldbUrl) { + PolicyController.xacmldbUrl = xacmldbUrl; + } + + public static String getXacmldbUserName() { + return xacmldbUserName; + } + + public static void setXacmldbUserName(String xacmldbUserName) { + PolicyController.xacmldbUserName = xacmldbUserName; + } + + public static String getXacmldbPassword() { + return xacmldbPassword; + } + + public static void setXacmldbPassword(String xacmldbPassword) { + PolicyController.xacmldbPassword = xacmldbPassword; + } + + public static String getAutoPushAvailable() { + return autoPushAvailable; + } + + public static void setAutoPushAvailable(String autoPushAvailable) { + PolicyController.autoPushAvailable = autoPushAvailable; + } + + public static String getAutoPushDSClosedLoop() { + return autoPushDSClosedLoop; + } + + public static void setAutoPushDSClosedLoop(String autoPushDSClosedLoop) { + PolicyController.autoPushDSClosedLoop = autoPushDSClosedLoop; + } + + public static String getAutoPushDSFirewall() { + return autoPushDSFirewall; + } + + public static void setAutoPushDSFirewall(String autoPushDSFirewall) { + PolicyController.autoPushDSFirewall = autoPushDSFirewall; + } + + public static String getAutoPushDSMicroservice() { + return autoPushDSMicroservice; + } + + public static void setAutoPushDSMicroservice(String autoPushDSMicroservice) { + PolicyController.autoPushDSMicroservice = autoPushDSMicroservice; + } + + public static String getAutoPushPDPGroup() { + return autoPushPDPGroup; + } + + public static void setAutoPushPDPGroup(String autoPushPDPGroup) { + PolicyController.autoPushPDPGroup = autoPushPDPGroup; + } + + public static String getPapUrl() { + return papUrl; + } + + public static void setPapUrl(String papUrl) { + PolicyController.papUrl = papUrl; + } + + public static String getMsOnapName() { + return msOnapName; + } + + public static void setMsOnapName(String msOnapName) { + PolicyController.msOnapName = msOnapName; + } + + public static String getMsPolicyName() { + return msPolicyName; + } + + public static void setMsPolicyName(String msPolicyName) { + PolicyController.msPolicyName = msPolicyName; + } + + public static String getConfigHome() { + return configHome; + } + + public static void setConfigHome(String configHome) { + PolicyController.configHome = configHome; + } + + public static String getActionHome() { + return actionHome; + } + + public static void setActionHome(String actionHome) { + PolicyController.actionHome = actionHome; + } + + public static Object getMapaccess() { + return mapAccess; + } + + public static String getPolicydata() { + return policyData; + } + + public static String getCharacterencoding() { + return characterEncoding; + } + + public static String getContenttype() { + return contentType; + } + + public static String getFile() { + return file; + } +} + diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java new file mode 100644 index 000000000..92794dda9 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java @@ -0,0 +1,384 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.model.Roles; +import org.onap.policy.rest.adapter.PolicyExportAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.ActionBodyEntity; +import org.onap.policy.rest.jpa.ConfigurationDataEntity; +import org.onap.policy.rest.jpa.PolicyEditorScopes; +import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.rest.jpa.PolicyVersion; +import org.onap.policy.rest.jpa.UserInfo; +import org.onap.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; + + private PolicyController policyController; + public PolicyController getPolicyController() { + return policyController; + } + + public void setPolicyController(PolicyController policyController) { + this.policyController = policyController; + } + + public static CommonClassDao getCommonClassDao() { + return commonClassDao; + } + + public static void setCommonClassDao(CommonClassDao commonClassDao) { + PolicyExportAndImportController.commonClassDao = commonClassDao; + } + + @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 = policyController != null ? getPolicyController() : 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 = controller.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/onap/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java new file mode 100644 index 000000000..f3291a79b --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.rest.dao.CommonClassDao; +import org.onap.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/onap/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java new file mode 100644 index 000000000..6f8b3de8e --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyEditorScopes; +import org.onap.policy.rest.jpa.PolicyRoles; +import org.onap.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{ + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyRolesController.class); + + @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){ + LOGGER.error("Exception Occured"+e); + } + } + + @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){ + LOGGER.error("Exception Occured"+e); + } + 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){ + LOGGER.error("Exception Occured"+e); + } + } +} + +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/onap/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java new file mode 100644 index 000000000..5fb0c1a7e --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java @@ -0,0 +1,776 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.controller; + + +import java.io.ByteArrayInputStream; +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.LinkedHashMap; +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.SAXParser; +import javax.xml.parsers.SAXParserFactory; + +import org.apache.commons.lang.StringUtils; +import org.dom4j.util.XMLErrorHandler; +import org.json.JSONObject; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.ClosedLoopFaultBody; +import org.onap.policy.rest.adapter.ClosedLoopPMBody; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.MicroServiceModels; +import org.onap.policy.rest.jpa.SafePolicyWarning; +import org.onap.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.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 { + + private static final Logger LOGGER = FlexLogger.getLogger(PolicyValidationController.class); + + 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 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; + StringBuilder responseString = new StringBuilder(); + 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.append("PolicyName:" + policyNameValidate + "
    "); + valid = false; + }; + }else{ + responseString.append( "PolicyName: PolicyName Should not be empty" + "
    "); + valid = false; + } + if(policyData.getPolicyDescription() != null){ + String descriptionValidate = descriptionValidator(policyData.getPolicyDescription()); + if(!descriptionValidate.contains("success")){ + responseString.append("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.getOnapName() != null){ + String onapNameValidate = emptyValidator(policyData.getOnapName()); + if(!onapNameValidate.contains("success")){ + responseString.append("OnapName:" + onapNameValidate + "
    "); + valid = false; + } + }else{ + responseString.append("Onap Name: Onap Name Should not be empty" + "
    "); + valid = false; + } + } + + if(policyData.getRiskType() != null){ + String riskTypeValidate = emptyValidator(policyData.getRiskType()); + if(!riskTypeValidate.contains("success")){ + responseString.append("RiskType:" + riskTypeValidate + "
    "); + valid = false; + } + }else { + responseString.append("Risk Type: Risk Type Should not be Empty" + "
    "); + valid = false; + } + + if(policyData.getRiskLevel() != null){ + String validateRiskLevel = emptyValidator(policyData.getRiskLevel()); + if(!validateRiskLevel.contains("success")){ + responseString.append("RiskLevel:" + validateRiskLevel + "
    "); + valid = false; + } + }else { + responseString.append("Risk Level: Risk Level Should not be Empty" + "
    "); + valid = false; + } + + if(policyData.getGuard() != null){ + String validateGuard = emptyValidator(policyData.getGuard()); + if(!validateGuard.contains("success")){ + responseString.append("Guard:" + validateGuard + "
    "); + valid = false; + } + }else { + responseString.append("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.append("ConfigName:" + configNameValidate + "
    "); + valid = false; + } + }else{ + responseString.append("Config Name: Config Name Should not be Empty" + "
    "); + valid = false; + } + if(policyData.getConfigType() != null){ + String configTypeValidate = emptyValidator(policyData.getConfigType()); + if(!configTypeValidate.contains("success")){ + responseString.append("ConfigType:" + configTypeValidate + "
    "); + valid = false; + } + }else{ + responseString.append("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.append("Config Body: JSON Content is not valid" + "
    "); + valid = false; + } + } else if (policyType.equals("XML")) { + if (!isXMLValid(configBodyData)) { + responseString.append("Config Body: XML Content data is not valid" + "
    "); + valid = false; + } + } else if (policyType.equals("PROPERTIES")) { + if (!isPropValid(configBodyData)||configBodyData.equals("")) { + responseString.append("Config Body: Property data is not valid" + "
    "); + valid = false; + } + } else if (policyType.equals("OTHER")) { + if (configBodyData.equals("")) { + responseString.append("Config Body: Config Body Should not be Empty" + "
    "); + valid = false; + } + } + } + }else{ + responseString.append("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.append("ConfigName:" + configNameValidate + "
    "); + valid = false; + } + }else{ + responseString.append("Config Name: Config Name is required" + "
    "); + valid = false; + } + if(policyData.getSecurityZone() == null){ + responseString.append("Security Zone: Security Zone is required" + "
    "); + valid = false; + } + } + if(policyData.getConfigPolicyType().equals("BRMS_Param")){ + if(policyData.getRuleName() == null){ + responseString.append("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.append("Raw Rule Validate:Raw Rule has error"+ message +"
    "); + valid = false; + } + }else{ + responseString.append("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.append("ServiceType PolicyName:ServiceType PolicyName is required
    "); + valid = false; + } + }catch(Exception e){ + responseString.append("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.toString()); + if(result != "success"){ + responseString.append(result + "
    "); + valid = false; + } + } + if(pmBody.getGeoLink() != null){ + String result = PolicyUtils.emptyPolicyValidator(pmBody.getGeoLink()); + if(!result.contains("success")){ + responseString.append("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.append("Attributes:" + key + " : value has spaces
    "); + valid = false; + }; + } + } + } + }else{ + responseString.append("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.toString()); + if(result != "success"){ + responseString.append(result+ "
    "); + valid = false; + } + } + if((faultBody.isGama() || faultBody.isMcr() || faultBody.isTrinity() || faultBody.isvDNS() || faultBody.isvUSP()) != true){ + responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "); + valid = false; + } + if(faultBody.getActions() == null){ + responseString.append("vPRO Actions:vPRO Actions is required
    "); + valid = false; + } + if(faultBody.getClosedLoopPolicyStatus() == null){ + responseString.append("Policy Status:Policy Status is required
    "); + valid = false; + } + if(faultBody.getConditions() == null){ + responseString.append("Conditions:Select Atleast one Condition
    "); + valid = false; + } + if(faultBody.getGeoLink() != null){ + String result = PolicyUtils.emptyPolicyValidatorWithSpaceAllowed(faultBody.getGeoLink()); + if(!result.contains("success")){ + responseString.append("GeoLink:" + result + "
    "); + valid = false; + }; + } + + if(faultBody.getTimeInterval() == 0){ + responseString.append("Time Interval:Time Interval is required
    "); + valid = false; + } + if(faultBody.getRetrys() == 0){ + responseString.append("Number of Retries:Number of Retries is required
    "); + valid = false; + } + if(faultBody.getTimeOutvPRO() == 0){ + responseString.append("APP-C Timeout:APP-C Timeout is required
    "); + valid = false; + } + if(faultBody.getTimeOutRuby() == 0){ + responseString.append("TimeOutRuby:TimeOutRuby is required
    "); + valid = false; + } + if(faultBody.getVnfType() == null){ + responseString.append("Vnf Type:Vnf Type is required
    "); + valid = false; + } + }else{ + responseString.append("D2/Virtualized Services:Select atleast one D2/Virtualized Services
    "); + responseString.append("vPRO Actions:vPRO Actions is required
    "); + responseString.append("Aging Window:Aging Window is required
    "); + responseString.append("Policy Status:Policy Status is required
    "); + responseString.append("Conditions:Select Atleast one Condition
    "); + responseString.append("PEP Name:PEP Name is required
    "); + responseString.append("PEP Action:PEP Action is required
    "); + responseString.append("Time Interval:Time Interval is required
    "); + responseString.append("Number of Retries:Number of Retries is required
    "); + responseString.append("APP-C Timeout:APP-C Timeout is required
    "); + responseString.append("TimeOutRuby:TimeOutRuby is required
    "); + responseString.append("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)){ + Map 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 (PolicyUtils.isInteger(value.replace("\"", ""))){ + int result = Integer.parseInt(value.replace("\"", "")); + if (result < startNum || result > endNum){ + responseString.append(returnString); + valid = false; + } + }else { + responseString.append(returnString); + valid = false; + } + } + } + } + }else{ + responseString.append("Micro Service: Micro Service is required" + "
    "); + valid = false; + } + + if(policyData.getPriority() == null){ + responseString.append("Priority: Priority is required" + "
    "); + valid = false; + } + } + } + if (policyData.getPolicyType().equals(DECISION_POLICY)){ + if(policyData.getOnapName() != null){ + String onapNameValidate = emptyValidator(policyData.getOnapName()); + if(!onapNameValidate.contains("success")){ + responseString.append("OnapName:" + onapNameValidate + "
    "); + valid = false; + } + }else{ + responseString.append("Onap Name: Onap Name Should not be empty" + "
    "); + valid = false; + } + + if("Rainy_Day".equals(policyData.getRuleProvider())){ + if(policyData.getRainyday()==null){ + responseString.append(" Rainy Day Parameters are Required
    "); + valid = false; + }else{ + if(policyData.getRainyday().getServiceType()==null){ + responseString.append("Rainy Day Service Type is Required
    "); + valid = false; + } + if(policyData.getRainyday().getVnfType()==null){ + responseString.append("Rainy Day VNF Type is Required
    "); + valid = false; + } + if(policyData.getRainyday().getBbid()==null){ + responseString.append("Rainy Day Building Block ID is Required
    "); + valid = false; + } + if(policyData.getRainyday().getWorkstep()==null){ + responseString.append("Rainy Day Work Step is Required
    "); + valid = false; + } + if(policyData.getRainyday().getServiceType()==null){ + responseString.append("Rainy Day Error Code is Required
    "); + valid = false; + } + } + } + + if("GUARD_YAML".equals(policyData.getRuleProvider()) || "GUARD_BL_YAML".equals(policyData.getRuleProvider())){ + if(policyData.getYamlparams()==null){ + responseString.append(" Guard Params are Required " + "
    "); + valid = false; + }else{ + if(policyData.getYamlparams().getActor()==null){ + responseString.append("Guard Params Actor is Required " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getRecipe()==null){ + responseString.append("Guard Params Recipe is Required " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getGuardActiveStart()==null){ + responseString.append("Guard Params Guard Active Start/b>is Required " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getGuardActiveEnd()==null){ + responseString.append("Guard Params Guard Active Endis Required " + "
    "); + valid = false; + } + if("GUARD_YAML".equals(policyData.getRuleProvider())){ + if(policyData.getYamlparams().getLimit()==null){ + responseString.append(" Guard Params Limit is Required " + "
    "); + valid = false; + }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getLimit())){ + responseString.append(" Guard Params Limit Should be Integer " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getTimeWindow()==null){ + responseString.append("Guard Params Time Window is Required" + "
    "); + valid = false; + }else if(!PolicyUtils.isInteger(policyData.getYamlparams().getTimeWindow())){ + responseString.append(" Guard Params Time Window Should be Integer " + "
    "); + valid = false; + } + if(policyData.getYamlparams().getTimeUnits()==null){ + responseString.append("Guard Params Time Units is Required" + "
    "); + valid = false; + } + }else if("GUARD_BL_YAML".equals(policyData.getRuleProvider())){ + if(policyData.getYamlparams().getBlackList()==null || policyData.getYamlparams().getBlackList().isEmpty()){ + responseString.append(" Guard Params BlackList is Required " + "
    "); + valid = false; + }else{ + for(String blackList: policyData.getYamlparams().getBlackList()){ + if(blackList==null || !("success".equals(emptyValidator(blackList)))){ + responseString.append(" Guard Params BlackList Should be valid String" + "
    "); + valid = false; + break; + } + } + } + } + } + } + } + + if(policyData.getPolicyType().equals(ACTION_POLICY)){ + if(policyData.getActionPerformer() != null){ + String actionPerformer = emptyValidator(policyData.getActionPerformer()); + if(!actionPerformer.contains("success")){ + responseString.append("ActionPerformer:" + actionPerformer + "
    "); + valid = false; + }; + }else{ + responseString.append("ActionPerformer: ActionPerformer Should not be empty" + "
    "); + valid = false; + } + if(policyData.getAttributes() != null){ + for(Object attribute : policyData.getAttributes()){ + if(attribute instanceof LinkedHashMap){ + try{ + //This is for validation check if the value exists or not + String key = ((LinkedHashMap) attribute).get("key").toString(); + String value = ((LinkedHashMap) attribute).get("value").toString(); + if("".equals(key) || "".equals(value)){ + responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
    "); + valid = false; + break; + } + }catch(Exception e){ + LOGGER.error("This is a Policy Validation check" +e); + responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
    "); + valid = false; + break; + } + } + } + }else{ + responseString.append("Component Attributes: One or more Fields in Component Attributes is Empty." + "
    "); + valid = false; + } + if(policyData.getActionAttributeValue() != null){ + String actionAttribute = emptyValidator(policyData.getActionAttributeValue()); + if(!actionAttribute.contains("success")){ + responseString.append("ActionAttribute:" + actionAttribute + "
    "); + valid = false; + }; + }else{ + responseString.append("ActionAttribute: ActionAttribute Should not be empty" + "
    "); + valid = false; + } + } + + if(policyData.getPolicyType().equals(ACTION_POLICY) || policyData.getPolicyType().equals(DECISION_POLICY)){ + if(!policyData.getRuleAlgorithmschoices().isEmpty()){ + for(Object attribute : policyData.getRuleAlgorithmschoices()){ + if(attribute instanceof LinkedHashMap){ + try{ + String label = ((LinkedHashMap) attribute).get("id").toString(); + String key = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = ((LinkedHashMap) attribute).get("dynamicRuleAlgorithmField2").toString(); + if("".equals(label) || "".equals(key) || "".equals(rule) || "".equals(value)){ + responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
    "); + valid = false; + } + }catch(Exception e){ + LOGGER.error("This is a Policy Validation check" +e); + responseString.append("Rule Algorithms: One or more Fields in Rule Algorithms is Empty." + "
    "); + valid = false; + break; + } + } + } + } + } + + if(policyData.getPolicyType().equals(CONFIG_POLICY)){ + String value = ""; + if(valid){ + List spData = commonClassDao.getDataById(SafePolicyWarning.class, "riskType", policyData.getRiskType()); + if (!spData.isEmpty()){ + SafePolicyWarning safePolicyWarningData = (SafePolicyWarning) spData.get(0); + safePolicyWarningData.getMessage(); + value = "Message:" + safePolicyWarningData.getMessage(); + } + responseString.append("success" + "@#"+ value); + } + }else{ + if(valid){ + responseString.append("success"); + } + } + + PrintWriter out = response.getWriter(); + JsonMessage msg = new JsonMessage(mapper.writeValueAsString(responseString.toString())); + JSONObject j = new JSONObject(msg); + out.write(j.toString()); + + return null; + } + catch (Exception e){ + LOGGER.error("Exception Occured while Policy Validation" +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; + if ("".equals(field) || 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; + 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 response){ + if(email != null){ + String validateEmail = PolicyUtils.validateEmailAddress(email.replace("\"", "")); + if(!validateEmail.contains("success")){ + response += "Email:" + validateEmail+ "
    "; + }else{ + return "success"; + } + } + return response; + } + + 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()); + } + } + } + } + + // Validation for json. + protected static boolean isJSONValid(String data) { + JsonReader jsonReader = null; + try { + new JSONObject(data); + InputStream stream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)); + jsonReader = Json.createReader(stream); + LOGGER.info("Json Value is: " + jsonReader.read().toString() ); + } catch (Exception e) { + LOGGER.error("Exception Occured While Validating"+e); + return false; + }finally{ + if(jsonReader != null){ + jsonReader.close(); + } + } + 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 (Exception e) { + LOGGER.error("Exception Occured While Validating"+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 = 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; + } + +} \ No newline at end of file diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java new file mode 100644 index 000000000..9cc6314dd --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/dao/SystemLogDbDao.java @@ -0,0 +1,33 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.dao; + + +import java.util.List; + +import org.onap.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/onap/policy/daoImp/CommonClassDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java new file mode 100644 index 000000000..05bf50f1b --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/CommonClassDaoImpl.java @@ -0,0 +1,382 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.dao.CommonClassDao; +import org.onap.policy.rest.jpa.PolicyRoles; +import org.onap.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) { + 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); + 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/onap/policy/daoImp/SystemLogDbDaoImpl.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java new file mode 100644 index 000000000..4fa64ceb3 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/daoImp/SystemLogDbDaoImpl.java @@ -0,0 +1,93 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.daoImp; + + +import java.util.List; + +import org.hibernate.Criteria; +import org.hibernate.Session; +import org.springframework.stereotype.Service; + +import org.onap.policy.xacml.api.XACMLErrorConstants; + +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.onap.policy.conf.HibernateSession; +import org.onap.policy.controller.PolicyController; +import org.onap.policy.dao.SystemLogDbDao; +import org.onap.policy.rest.jpa.SystemLogDB; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.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.getLogTableLimit()+""; + 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.getSystemAlertTableLimit()+""; + 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/onap/policy/model/PDPGroupContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java new file mode 100644 index 000000000..ae2144b10 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPGroupContainer.java @@ -0,0 +1,522 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.utils.PolicyContainer; +import org.onap.policy.utils.PolicyItemSetChangeNotifier; +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.policy.xacml.api.pap.OnapPDP; +import org.onap.policy.xacml.api.pap.OnapPDPGroup; +import org.onap.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. + */ + private static String PROPERTY_ID = "Id"; + + /** + * String identifier of a file's "name" property. + */ + private static String PROPERTY_NAME = "Name"; + + /** + * String identifier of a file's "Description" property. + */ + private static String PROPERTY_DESCRIPTION = "Description"; + + /** + * String identifier of a file's "Default" property. + */ + private static String PROPERTY_DEFAULT = "Default"; + /** + * String identifier of a file's "Status" property. + */ + private static String PROPERTY_STATUS = "Status"; + + /** + * String identifier of a file's "PDPs" property. + */ + private static String PROPERTY_PDPS = "PDPs"; + + /** + * String identifier of a file's "Policies" property. + */ + private static String PROPERTY_POLICIES = "Policies"; + + /** + * String identifier of a file's "PIP Configurations" property. + */ + private static String PROPERTY_PIPCONFIG = "PIP Configurations"; + + /** + * String identifier of a file's "Selected" property. + */ + private static String PROPERTY_SELECTED = "Selected"; + + /** + * List of the string identifiers for the available properties. + */ + private 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 OnapPDPGroup) { + return true; + } + return false; + } + + public synchronized void refreshGroups() { + synchronized(this.groups) { + this.groups.clear(); + try { + this.groups.addAll(this.papEngine.getOnapPDPGroups()); + } 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(OnapPDPGroup 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(OnapPDPGroup group, OnapPDPGroup 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(OnapPDP pdp, OnapPDPGroup 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(OnapPDP pdp) { + try { + papEngine.updatePDP(pdp); + } catch (PAPException e) { + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + e); + } + } + + public void updateGroup(OnapPDPGroup 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, OnapPDPGroup 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(OnapPDP pdp, OnapPDPGroup 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 (((OnapPDPGroup) 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((OnapPDPGroup) 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 OnapPDPGroup group; + + public PDPGroupItem(OnapPDPGroup 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/onap/policy/model/PDPPolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java new file mode 100644 index 000000000..864078439 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/PDPPolicyContainer.java @@ -0,0 +1,348 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.model; + + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.onap.policy.utils.PolicyContainer; +import org.onap.policy.utils.PolicyItemSetChangeNotifier; +import org.onap.policy.common.logging.flexlogger.*; + +import org.onap.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.onap.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. + */ + private static String PROPERTY_ID = "Id"; + + /** + * String identifier of a file's "name" property. + */ + private static String PROPERTY_NAME = "Name"; + + /** + * String identifier of a file's "name" property. + */ + private static String PROPERTY_VERSION = "Version"; + + /** + * String identifier of a file's "Description" property. + */ + private static String PROPERTY_DESCRIPTION = "Description"; + + /** + * String identifier of a file's "IsRoot" property. + */ + private static String PROPERTY_ISROOT = "Root"; + + /** + * List of the string identifiers for the available properties. + */ + private 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/onap/policy/model/Roles.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java new file mode 100644 index 000000000..51e78d0e5 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/model/Roles.java @@ -0,0 +1,99 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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/onap/policy/utils/ConfigurableRESTUtils.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java new file mode 100644 index 000000000..3e935dd74 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/ConfigurableRESTUtils.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.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; + } + + private String ERROR_RECEIVED = "ERROR - Unexpected HTTP response: "; + + public ConfigurableRESTUtils() { + //Default Constructor + } + + + /** + * 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) { + LOGGER.error("Exception Occured"+e1); + } + 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/onap/policy/utils/PolicyContainer.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyContainer.java new file mode 100644 index 000000000..d014af031 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyContainer.java @@ -0,0 +1,121 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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/onap/policy/utils/PolicyItemSetChangeNotifier.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyItemSetChangeNotifier.java new file mode 100644 index 000000000..92764aa4f --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/PolicyItemSetChangeNotifier.java @@ -0,0 +1,95 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.policy.utils; + + +import java.io.Serializable; +import java.util.Collection; +import java.util.EventObject; +import java.util.LinkedList; + +import org.onap.policy.utils.PolicyContainer.ItemSetChangeEvent; +import org.onap.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/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java new file mode 100644 index 000000000..f3e72cb92 --- /dev/null +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/utils/XACMLPolicyWriterWithPapNotify.java @@ -0,0 +1,483 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP 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.onap.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.onap.policy.rest.XACMLRestProperties; + +import org.onap.policy.xacml.api.XACMLErrorConstants; +import org.onap.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.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.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