From 91d04c64771832a0b8815ffbe1f0f9920320d94d Mon Sep 17 00:00:00 2001 From: Pamela Dragosh Date: Tue, 14 Feb 2017 19:41:00 -0500 Subject: Initial OpenECOMP policy/engine commit Change-Id: I7dbff37733b661643dd4d1caefa3d7dccc361b6e Signed-off-by: Pamela Dragosh --- .../java/org/openecomp/policy/admin/CheckPDP.java | 187 +++ .../policy/admin/PAPNotificationBroadcaster.java | 120 ++ .../policy/admin/PolicyManagerServlet.java | 1334 ++++++++++++++++++++ .../policy/admin/PolicyNotificationMail.java | 140 ++ .../openecomp/policy/admin/RESTfulPAPEngine.java | 732 +++++++++++ .../org/openecomp/policy/admin/XacmlAdminUI.java | 266 ++++ 6 files changed, 2779 insertions(+) create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/CheckPDP.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PAPNotificationBroadcaster.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java create mode 100644 ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/XacmlAdminUI.java (limited to 'ecomp-sdk-app/src/main/java/org/openecomp/policy/admin') diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/CheckPDP.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/CheckPDP.java new file mode 100644 index 000000000..f1447f135 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/CheckPDP.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Base64; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Properties; + +import org.openecomp.policy.rest.XACMLRestProperties; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import com.att.research.xacml.util.XACMLProperties; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +public class CheckPDP { + private static Path pdpPath = null; + private static Properties pdpProp = null; + private static Long oldModified = null; + private static Long newModified = null; + private static HashMap pdpMap = null; + private static final Logger logger = FlexLogger.getLogger(CheckPDP.class); + + public static boolean validateID(String id) { + // ReadFile + try { + readFile(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + return false; + } + // Check ID + if (pdpMap.containsKey(id)) { + return true; + } + return false; + } + + private static void readFile() throws Exception { + String pdpFile = null; + try{ + pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); + }catch (Exception e){ + logger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot read the PDP ID File"); + return; + } + if (pdpFile == null) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile); + } + if (pdpPath == null) { + pdpPath = Paths.get(pdpFile); + if (Files.notExists(pdpPath)) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path : " + pdpPath.toString()); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString()); + } + if (pdpPath.toString().endsWith(".properties")) { + readProps(); + } else { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file " + pdpFile); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file"); + } + } + // Check if File is updated recently + else { + newModified = pdpPath.toFile().lastModified(); + if (newModified != oldModified) { + // File has been updated. + readProps(); + } + } + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + private static void readProps() throws Exception { + InputStream in; + pdpProp = new Properties(); + try { + in = new FileInputStream(pdpPath.toFile()); + oldModified = pdpPath.toFile().lastModified(); + pdpProp.load(in); + } catch (IOException e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + throw new Exception("Cannot Load the Properties file", e); + } + // Read the Properties and Load the PDPs and encoding. + pdpMap = new HashMap(); + // Check the Keys for PDP_URLs + Collection unsorted = pdpProp.keySet(); + List sorted = new ArrayList(unsorted); + Collections.sort(sorted); + for (String propKey : sorted) { + if (propKey.startsWith("PDP_URL")) { + String check_val = pdpProp.getProperty(propKey); + if (check_val == null) { + throw new Exception("Properties file doesn't have the PDP_URL parameter"); + } + if (check_val.contains(";")) { + List pdp_default = new ArrayList(Arrays.asList(check_val.split("\\s*;\\s*"))); + int pdpCount = 0; + while (pdpCount < pdp_default.size()) { + String pdpVal = pdp_default.get(pdpCount); + readPDPParam(pdpVal); + pdpCount++; + } + } else { + readPDPParam(check_val); + } + } + } + if (pdpMap == null || pdpMap.isEmpty()) { + logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); + throw new Exception(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs"); + } + } + + private static void readPDPParam(String pdpVal) throws Exception{ + if(pdpVal.contains(",")){ + List pdpValues = new ArrayList(Arrays.asList(pdpVal.split("\\s*,\\s*"))); + if(pdpValues.size()==3){ + // 1:2 will be UserID:Password + String userID = pdpValues.get(1); + String pass = pdpValues.get(2); + Base64.Encoder encoder = Base64.getEncoder(); + // 0 - PDPURL + pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); + }else{ + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpValues); + throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); + } + }else{ + logger.error(XACMLErrorConstants.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); + throw new Exception(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request."); + } + } + + public static String getEncoding(String pdpID){ + try { + readFile(); + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + String encoding = null; + if(pdpMap!=null && (!pdpMap.isEmpty())){ + try{ + encoding = pdpMap.get(pdpID); + } catch(Exception e){ + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + e); + } + return encoding; + }else{ + return null; + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PAPNotificationBroadcaster.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PAPNotificationBroadcaster.java new file mode 100644 index 000000000..cff0828e2 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PAPNotificationBroadcaster.java @@ -0,0 +1,120 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + + +import java.io.Serializable; +import java.util.LinkedList; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +/** + * Handle Notifications from the PAP that the PDP Groups have been changed. + * We need a Server Push Broadcaster because there may be multiple Vaadin instances (i.e. Users) that need to be told when a change occurs. + * + * Initially we only update the entire set of PDPGroups in one shot. + * + * (Code copied from Book of Vaadin chapter on Server Push + * + */ +public class PAPNotificationBroadcaster implements Serializable { + /** + * + */ + private static final long serialVersionUID = -2539940306348821754L; + + + private static Logger logger = FlexLogger.getLogger(PAPNotificationBroadcaster.class); + + + static ExecutorService executorService = Executors.newSingleThreadExecutor(); + + /** + * Interface used by all classes that need to be notified when PAP sends an update message. + * + * + */ + public interface PAPNotificationBroadcastListener { + void updateAllGroups(); + } + + + + /* + * list of registered listeners + */ + private static LinkedList listeners = + new LinkedList(); + + /** + * Listener registers to hear about updates. + * @param listener + */ + public static synchronized void register( + PAPNotificationBroadcastListener listener) { + listeners.add(listener); + } + + + /** + * Listener is going away. + * + * @param listener + */ + public static synchronized void unregister( + PAPNotificationBroadcastListener listener) { + listeners.remove(listener); + } + + + + /** + * Tell all listeners about an update. + * + * @param message + */ + public static synchronized void updateAllGroups() { + for (final PAPNotificationBroadcastListener listener: listeners) { + // Original code copied from example: + // executorService.execute(new Runnable() { + // @Override + // public void run() { + // The problem with this is that the execute starts a new Thread, but the thing we are calling (the listener.updateAllGroups) + // happens in this case to ALSO create a new thread, and it locks up because the shared threadpool queue is already locked by this method. + // On application shutdown that left us with a blocked thread, so the process never goes away. + // Since the listener.updateAllGroups does ALL of its work inside a new Runnable thread, there should be no need for this method to also create a thread. + + /* + * IMPORTANT: + * All listeners MUST either execute with no possibility of blocking + * OR must start their own threads to handle blocking and concurrent operations. + */ + if (logger.isDebugEnabled()) { + logger.debug("updateAllGroups"); + } + listener.updateAllGroups(); + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java new file mode 100644 index 000000000..e355b8295 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyManagerServlet.java @@ -0,0 +1,1334 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +/* + * + * + * + * */ +package org.openecomp.policy.admin; + + +import java.io.BufferedOutputStream; +import java.io.BufferedReader; +import java.io.File; +import java.io.FileFilter; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; +import java.nio.file.DirectoryStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.BasicFileAttributes; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import javax.servlet.ServletException; +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.commons.io.FileUtils; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.filefilter.WildcardFileFilter; +import org.apache.http.HttpStatus; +import org.json.JSONException; +import org.json.JSONObject; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.components.HumanPolicyComponent; +import org.openecomp.policy.controller.ActionPolicyController; +import org.openecomp.policy.controller.CreateBRMSParamController; +import org.openecomp.policy.controller.CreateBRMSRawController; +import org.openecomp.policy.controller.CreateClosedLoopFaultController; +import org.openecomp.policy.controller.CreateClosedLoopPMController; +import org.openecomp.policy.controller.CreateDcaeMicroServiceController; +import org.openecomp.policy.controller.CreateFirewallController; +import org.openecomp.policy.controller.CreatePolicyController; +import org.openecomp.policy.controller.DecisionPolicyController; +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.controller.PolicyExportAndImportController; +import org.openecomp.policy.elk.client.ElkConnector; +import org.openecomp.policy.model.Roles; +import org.openecomp.policy.rest.jpa.PolicyEditorScopes; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.UserInfo; +import org.openecomp.policy.utils.XACMLPolicyWriterWithPapNotify; +import org.openecomp.portalsdk.core.web.support.UserUtils; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.util.XACMLPolicyScanner; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class PolicyManagerServlet extends HttpServlet { + private static final Logger LOG = FlexLogger.getLogger(PolicyManagerServlet.class); + private static final long serialVersionUID = -8453502699403909016L; + + private enum Mode { + LIST, RENAME, COPY, DELETE, EDITFILE, ADDFOLDER, DESCRIBEPOLICYFILE, VIEWPOLICY, ADDSUBSCOPE, SWITCHVERSION, EXPORT + } + + public static final String REPOSITORY_BASE_PATH = PolicyController.getGitPath().toString(); + private static String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss"; + public static final String CONFIG_HOME = PolicyController.getConfigHome(); + public static final String ACTION_HOME = PolicyController.getActionHome(); + private static String CONTENTTYPE = "application/json"; + private File repofilePath; + 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 String REPOSITORY = "repository"; + + private static String CONFIG = "Config_"; + private static String ACTION = "Action_"; + private static String DECISION = "Decision_"; + + @Override + public void init() throws ServletException { + super.init(); + } + + @Override + public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + String path = request.getParameter("path"); + File file = new File(REPOSITORY_BASE_PATH, path); + + if (!file.isFile()) { + // if not a file, it is a folder, show this error. + response.sendError(HttpServletResponse.SC_NOT_FOUND, "Resource Not Found"); + return; + } + + response.setHeader("Content-Type", getServletContext().getMimeType(file.getName())); + response.setHeader("Content-Length", String.valueOf(file.length())); + response.setHeader("Content-Disposition", "inline; filename=\"" + file.getName() + "\""); + + FileInputStream input = null; + BufferedOutputStream output = null; + try { + input = new FileInputStream(file); + output = new BufferedOutputStream(response.getOutputStream()); + byte[] buffer = new byte[8192]; + for (int length = 0; (length = input.read(buffer)) > 0;) { + output.write(buffer, 0, length); + } + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Reading Imput Stream" + e); + } finally { + if (output != null) { + try { + output.close(); + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Closing Output Stream" + e); + } + } + if (input != null) { + try { + input.close(); + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Closing Input Stream" + e); + } + } + } + + } + + @Override + protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + LOG.debug("doPost"); + try { + // if request contains multipart-form-data + if (ServletFileUpload.isMultipartContent(request)) { + uploadFile(request, response); + } + // all other post request has json params in body + else { + fileOperation(request, response); + } + } catch (Exception e) { + setError(e, response); + } + } + + //Set Error Message for Exception + private void setError(Exception t, HttpServletResponse response) throws IOException { + try { + JSONObject responseJsonObject = error(t.getMessage()); + response.setContentType(CONTENTTYPE); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } catch (Exception x) { + response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, x.getMessage()); + } + } + + //Policy Import Functionality + private void uploadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException { + try { + String newFile; + Map files = new HashMap(); + + List items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); + for (FileItem item : items) { + if (!item.isFormField()) { + // Process form file field (input type="file"). + files.put(item.getName(), item.getInputStream()); + if(item.getName().endsWith(".tar")){ + try{ + File file = new File(item.getName()); + OutputStream outputStream = new FileOutputStream(file); + IOUtils.copy(item.getInputStream(), outputStream); + outputStream.close(); + newFile = file.toString(); + PolicyExportAndImportController importController = new PolicyExportAndImportController(); + importController.ImportRepositoryFile(newFile, request); + }catch(Exception e){ + LOG.error("Upload error : " + e); + } + } + } + } + + JSONObject responseJsonObject = null; + responseJsonObject = this.success(); + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } catch (Exception e) { + LOG.debug("Cannot write file"); + throw new ServletException("Cannot write file", e); + } + } + + //File Operation Functionality + private void fileOperation(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + JSONObject responseJsonObject = null; + try { + StringBuilder sb = new StringBuilder(); + BufferedReader br = request.getReader(); + String str; + while ((str = br.readLine()) != null) { + sb.append(str); + } + br.close(); + JSONObject jObj = new JSONObject(sb.toString()); + JSONObject params = jObj.getJSONObject("params"); + Mode mode = Mode.valueOf(params.getString("mode")); + switch (mode) { + case ADDFOLDER: + responseJsonObject = addFolder(params, request); + break; + case COPY: + responseJsonObject = copy(params, request); + break; + case DELETE: + responseJsonObject = delete(params, request); + break; + case EDITFILE: + responseJsonObject = editFile(params); + break; + case VIEWPOLICY: + responseJsonObject = editFile(params); + break; + case LIST: + responseJsonObject = list(params, request); + break; + case RENAME: + responseJsonObject = rename(params, request); + break; + case DESCRIBEPOLICYFILE: + responseJsonObject = describePolicy(params); + break; + case ADDSUBSCOPE: + responseJsonObject = addFolder(params, request); + break; + case SWITCHVERSION: + responseJsonObject = switchVersion(params, request); + break; + default: + throw new ServletException("not implemented"); + } + if (responseJsonObject == null) { + responseJsonObject = error("generic error : responseJsonObject is null"); + } + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While doing File Operation" + e); + responseJsonObject = error(e.getMessage()); + } + response.setContentType("application/json"); + PrintWriter out = response.getWriter(); + out.print(responseJsonObject); + out.flush(); + } + + //Switch Version Functionality + private JSONObject switchVersion(JSONObject params, HttpServletRequest request) throws ServletException{ + String path = params.getString("path"); + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + LOG.error("Exception Occured while reading userid from cookie" +e); + } + if(params.toString().contains("activeVersion")){ + String activeVersion = params.getString("activeVersion"); + String highestVersion = params.getString("highestVersion"); + if(Integer.parseInt(activeVersion) > Integer.parseInt(highestVersion)){ + return error("The Version shouldn't be greater than Highest Value"); + }else{ + String removeExtension = path.replace(".xml", ""); + String policyName = removeExtension.substring(0, removeExtension.lastIndexOf(".")); + String activePolicy = policyName + "." + activeVersion + ".xml"; + File file = new File(Paths.get(REPOSITORY_BASE_PATH, activePolicy).toString()); + if(!file.exists()){ + 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, "\\"); + } + String query = "update PolicyVersion set active_version='"+activeVersion+"' where policy_name ='" +policyName+"' and id >0"; + //query the database + PolicyController.updatePolicyVersion(query); + //Policy Notification + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(policyName); + entity.setActiveVersion(Integer.parseInt(activeVersion)); + entity.setModifiedBy(userId); + controller.WatchPolicyFunction(entity, policyName, "SwitchVersion"); + } + } + } + File policyFile = new File(REPOSITORY_BASE_PATH, path); + PolicyController policyController = new PolicyController(); + return policyController.SwitchVersionPolicyContent(policyFile); + } + + //Describe Policy + private JSONObject describePolicy(JSONObject params){ + String path = params.getString("path"); + File policyFile = new File(REPOSITORY_BASE_PATH, path); + + return HumanPolicyComponent.DescribePolicy(policyFile); + } + + //Get the List of Policies and Scopes for Showing in Editor tab + private JSONObject list(JSONObject params, HttpServletRequest request) throws ServletException { + Set scopes = null; + List roles = null; + try { + //Get the Login Id of the User from Request + String userId = UserUtils.getUserIdFromCookie(request); + //Check if the Role and Scope Size are Null get the values from db. + List userRoles = PolicyController.getRoles(userId); + roles = new ArrayList(); + scopes = new HashSet(); + for(Roles userRole: userRoles){ + roles.add(userRole.getRole()); + if(userRole.getScope() != null){ + if(userRole.getScope().contains(",")){ + String[] multipleScopes = userRole.getScope().split(","); + for(int i =0; i < multipleScopes.length; i++){ + scopes.add(multipleScopes[i]); + } + }else{ + scopes.add(userRole.getScope()); + } + } + } + if (roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST) ) { + if(scopes.isEmpty()){ + return error("No Scopes has been Assigned to the User. Please, Contact Super-Admin"); + } + } + + List resultList = new ArrayList(); + SimpleDateFormat dt = new SimpleDateFormat(DATE_FORMAT); + boolean onlyFolders = params.getBoolean("onlyFolders"); + String path = params.getString("path"); + if(path.contains("..xml")){ + path = path.replaceAll("..xml", "").trim(); + } + + + if("/".equals(path)){ + if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + try (DirectoryStream directoryStream = Files.newDirectoryStream(Paths.get(REPOSITORY_BASE_PATH, path))) { + for (Path pathObj : directoryStream) { + BasicFileAttributes attrs = Files.readAttributes(pathObj, BasicFileAttributes.class); + if (onlyFolders && !attrs.isDirectory()) { + continue; + } + JSONObject el = new JSONObject(); + String fileName = pathObj.getFileName().toString(); + if (!(fileName.equals(".DS_Store") || fileName.contains(".git"))) { + if(!fileName.endsWith(".xml")){ + el.put("name", fileName); + el.put("date", dt.format(new Date(attrs.lastModifiedTime().toMillis()))); + el.put("size", attrs.size()); + el.put("type", attrs.isDirectory() ? "dir" : "file"); + resultList.add(el); + } + } + } + } catch (IOException ex) { + LOG.error("Error Occured While reading Policy Files List"+ex ); + } + }else if(roles.contains(ADMIN) || roles.contains(EDITOR) || roles.contains(GUEST)){ + for(Object scope : scopes){ + JSONObject el = new JSONObject(); + Path filePath = Paths.get(REPOSITORY_BASE_PATH + File.separator + scope); + if(Files.exists(filePath)){ + el.put("name", scope); + el.put("date", dt.format(filePath.toFile().lastModified())); + el.put("size", ""); + el.put("type", "dir"); + resultList.add(el); + } + } + } + }else{ + try{ + String scopeName = path.substring(path.indexOf("/") +1); + activePolicyList(scopeName, resultList, roles, scopes, onlyFolders); + } catch (Exception ex) { + LOG.error("Error Occured While reading Policy Files List"+ex ); + } + } + + return new JSONObject().put(RESULT, resultList); + } catch (Exception e) { + LOG.error("list", e); + return error(e.getMessage()); + } + } + + //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){ + 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 = PolicyController.getListOfActivePolicies(query); + List scopesList = PolicyController.getListOfPolicyEditorScopes(scopeNamequery); + for(PolicyEditorScopes scopeById : scopesList){ + 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(scopeName.equalsIgnoreCase(checkScope)){ + JSONObject el = new JSONObject(); + Path filePath = Paths.get(REPOSITORY_BASE_PATH + File.separator + scope); + if(Files.exists(filePath)){ + el.put("name", filePath.getFileName()); + 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); + } + } + } + } + for (PolicyVersion policy : activePolicies) { + String scopeNameValue = policy.getPolicyName().substring(0, policy.getPolicyName().lastIndexOf(File.separator)); + String activepath = REPOSITORY_BASE_PATH + File.separator + policy.getPolicyName() + "." + policy.getActiveVersion() + ".xml"; + Path pathObj = Paths.get(activepath); + if(Files.exists(pathObj)){ + BasicFileAttributes attrs; + try { + attrs = Files.readAttributes(pathObj, BasicFileAttributes.class); + if (onlyFolders && !attrs.isDirectory()) { + continue; + } + if(roles.contains(SUPERADMIN) || roles.contains(SUPEREDITOR) || roles.contains(SUPERGUEST)){ + readPolicies(pathObj, attrs, scopeName, resultList); + }else if(!scopes.isEmpty()){ + for(String value : scopes){ + if(scopeNameValue.startsWith(value)){ + readPolicies(pathObj, attrs, scopeName, resultList); + } + } + } + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception occured while reading File Attributes"+e); + } + } + } + } + + //Read the Policy File to get Created by and Modified by User Name of Policy + public void readPolicies(Path pathObj, BasicFileAttributes attrs, String scopeName, List resultList){ + JSONObject el = new JSONObject(); + String policyName = ""; + String version = ""; + String scope = ""; + if(scopeName.contains("\\\\")){ + scopeName = scopeName.replace("\\\\", File.separator); + } + SimpleDateFormat dt = new SimpleDateFormat(DATE_FORMAT); + String fileName = pathObj.getFileName().toString(); + if (!(fileName.equals(".DS_Store") || fileName.startsWith(".git"))) { + if(fileName.endsWith(".xml")){ + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + fileName = fileName.substring(0, fileName.lastIndexOf('.')); + //Query the database + String parent = pathObj.toString().substring(pathObj.toString().indexOf(REPOSITORY)+ 11); + parent = FilenameUtils.removeExtension(parent); + version = parent.substring(parent.indexOf(".")+1); + policyName = parent.substring(0, parent.lastIndexOf(".")); + scope = policyName.substring(0, policyName.lastIndexOf(File.separator)); + if(policyName.contains("\\")){ + policyName = scope + "\\" + policyName.substring(policyName.lastIndexOf("\\")); + } + } + if(scopeName.equalsIgnoreCase(scope)){ + el.put("name", fileName); + if(pathObj.toFile().toString().endsWith(".xml")){ + el.put("version", version); + List createdByModifiedBy; + try { + createdByModifiedBy = XACMLPolicyScanner.getCreatedByModifiedBy(pathObj); + } catch (IOException e) { + LOG.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while Reading the Policy File" + pathObj.toString() + e.getMessage()); + createdByModifiedBy = Arrays.asList("", ""); + } + el.put("createdBy", getUserName(createdByModifiedBy.get(0))); + el.put("modifiedBy", getUserName(createdByModifiedBy.get(1))); + } + el.put("date", dt.format(new Date(attrs.lastModifiedTime().toMillis()))); + el.put("size", attrs.size()); + el.put("type", attrs.isDirectory() ? "dir" : "file"); + } + } + + if(!el.keySet().isEmpty()){ + resultList.add(el); + } + + } + + //Get the User Name based on ID from User Info table + public String getUserName(String userId) { + String userName = "super-admin"; + if("".equals(userId)){ + return userName; + } + try{ + return PolicyController.getUserName(userId); + }catch(Exception e){ + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Error Occured while Retriving User Name from User Info table"+e); + return userName; + } + } + + //Rename Policy + private JSONObject rename(JSONObject params, HttpServletRequest request) throws ServletException { + try { + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + LOG.error("Exception Occured while reading userid from cookie" +e); + } + String path = params.getString("path"); + String newpath = params.getString("newPath"); + LOG.debug("rename from: {} to: {}" +path + newpath); + + File srcFile = new File(REPOSITORY_BASE_PATH, path); + File destFile = new File(REPOSITORY_BASE_PATH, newpath); + if (srcFile.isFile()) { + renameXMLandConfig(destFile.getPath().toString(), srcFile.getPath().toString(), userId); + } else { + FileUtils.moveDirectory(srcFile, destFile); + String oldScopeName = path.substring(1).replace("/", File.separator); + String newScopeName = newpath.substring(1).replace("/", File.separator); + String scopeNamequery = "from PolicyEditorScopes where SCOPENAME like'" +oldScopeName.replace("\\", "\\\\\\\\")+"%'"; + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + List scopesList = PolicyController.getListOfPolicyEditorScopes(scopeNamequery); + for(PolicyEditorScopes scopes : scopesList){ + String scope = scopes.getScopeName(); + String newScope = scope.replace(oldScopeName, newScopeName); + scopes.setScopeName(newScope); + scopes.setUserModifiedBy(userInfo); + PolicyController.updatePolicyScopeEditor(scopes); + } + File[] list = destFile.listFiles(); + if(list.length > 0){ + renameXMLandConfig(destFile.getPath().toString(), srcFile.getPath().toString(), userId); + } + } + return success(); + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE+"Exception Occured While Renaming Policy"+e); + return error(e.getMessage()); + } + } + + //rename the xml and config files when renaming scope + public void renameXMLandConfig(String newPath, String oldPath, String loginId){ + if(!newPath.endsWith(".xml")){ + File dir = new File(newPath); + File[] listOfFiles = dir.listFiles(); + for(File file : listOfFiles){ + if(file.toString().endsWith(".xml")){ + renameFile(file, oldPath, newPath ); + }else if(file.isDirectory()){ + String oldFilePath = oldPath + File.separator +file.getName(); + renameXMLandConfig(file.toString(), oldFilePath, loginId); + } + } + }else{ + Path parent = Paths.get(oldPath.toString().substring(0, oldPath.toString().lastIndexOf(File.separator))); + String policyName = oldPath.toString().substring(oldPath.toString().indexOf(REPOSITORY) +11); + String removeExtension = policyName.replace(".xml", ""); + String dbPolicyName = removeExtension.substring(0, removeExtension.lastIndexOf(".")); + //Policy Notifcation + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(dbPolicyName); + entity.setModifiedBy(loginId); + controller.WatchPolicyFunction(entity, dbPolicyName, "Rename"); + String filterPolicyName = dbPolicyName.substring(dbPolicyName.lastIndexOf(File.separator)+1); + FileFilter fileFilter = new WildcardFileFilter(filterPolicyName + "." + "*" + ".xml"); + File[] files = parent.toFile().listFiles(fileFilter); + for(File file : files){ + String removeNewPathExtension = newPath.replace(".xml", ""); + String removeNewFileVersion = removeNewPathExtension.substring(0, removeNewPathExtension.lastIndexOf(".")); + String oldFile = file.getPath(); + oldFile = oldFile.replace(".xml", ""); + String version = oldFile.substring(oldFile.lastIndexOf(".")+1); + String finalPath = removeNewFileVersion + "." + version + ".xml"; + File destFile = new File(finalPath); + try { + FileUtils.moveFile(file, destFile); + renameFile(file, oldFile, finalPath); + } catch (IOException e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Renaming or Moving Policy"+e); + } + + } + } + } + + //Rename File + private void renameFile(File file, String oldPath, String newPath){ + if(file.toString().contains(CONFIG) || file.toString().contains(ACTION) || file.toString().contains(DECISION)){ + File xmlFileName = new File(newPath); + String oldfileWithExtension = null; + String filelocation = null; + String oldfile = null; + String newfile = null; + String extension = null; + if(newPath.endsWith(".xml")){ + extension = XACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(xmlFileName.toPath()); + }else{ + extension = XACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(file.toPath()); + String fileName = file.getName(); + oldPath = oldPath + File.separator + fileName; + newPath = newPath + File.separator + fileName; + } + + try{ + if(file.toString().contains(CONFIG)){ + filelocation = PolicyController.getConfigHome(); + } + if(file.toString().contains(ACTION)){ + filelocation = PolicyController.getActionHome(); + } + File oldFilePath = new File(oldPath); + String oldFileName = oldFilePath.getName().replace(".xml", ""); + File newFilePath = new File(newPath); + String newFileName = newFilePath.getName().replace(".xml", ""); + File target = new File(oldPath); + File newParentScope = new File(newPath); + if(newParentScope.toString().endsWith(".xml")){ + String newScope = newParentScope.toString().substring(0, newParentScope.toString().lastIndexOf(File.separator)); + newParentScope = new File(newScope); + } + String oldParentScope = target.toString().substring(0, target.toString().lastIndexOf(File.separator)); + String oldDomain = oldParentScope.toString().substring(oldParentScope.toString().indexOf(REPOSITORY) + 11); + if(oldDomain.endsWith(".xml")){ + oldDomain = oldDomain.substring(0, oldDomain.lastIndexOf(File.separator)); + } + oldfile = oldDomain + File.separator + oldFileName.substring(0, oldFileName.indexOf(".")); + if(oldDomain.contains(File.separator)){ + oldDomain = oldDomain.replace(File.separator, "."); + } + String newDomain = newParentScope.toString().substring(newParentScope.toString().indexOf(REPOSITORY) + 11); + newfile = newDomain + File.separator +newFileName.substring(0, newFileName.indexOf(".")); + if(newDomain.contains(File.separator)){ + newDomain = newDomain.replace(File.separator, "."); + } + if(file.toString().contains(CONFIG) || file.toString().contains(ACTION)){ + oldfileWithExtension = oldDomain + "." + oldFileName + "."+ extension; + String newfilewithExtension = newDomain + "." + newFileName + "." + extension; + File file1 = new File(filelocation, oldfileWithExtension); + file1.renameTo(new File(filelocation , newfilewithExtension)); + } + String query = "update PolicyVersion set policy_name='"+newfile.replace("\\", "\\\\")+"' where policy_name ='" +oldfile.replace("\\", "\\\\")+"' and id >0"; + //query the database + PolicyController.updatePolicyVersion(query); + }catch(Exception e){ + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Config file cannot found:" + oldfileWithExtension + e); + } + } + } + + //Clone the Policy + private JSONObject copy(JSONObject params, HttpServletRequest request) throws ServletException { + try { + String path = params.getString("path"); + String newpath = params.getString("newPath"); + LOG.debug("copy from: {} to: {}" + path +newpath); + File srcFile = new File(REPOSITORY_BASE_PATH, path); + File destFile = new File(REPOSITORY_BASE_PATH, newpath); + if (srcFile.isFile()) { + FileUtils.copyFile(srcFile, destFile); + cloneXMLandConfig(destFile, srcFile, request); + } else { + FileUtils.copyDirectory(srcFile, destFile); + } + return success(); + } catch (Exception e) { + LOG.error("copy", e); + return error(e.getMessage()); + } + } + + public void cloneXMLandConfig(File newPath, File oldPath, HttpServletRequest request){ + String userId = null; + try { + userId = UserUtils.getUserIdFromCookie(request); + } catch (Exception e) { + LOG.error("Exception Occured while reading userid from cookie" +e); + } + String newPolicyName = newPath.getPath().toString().substring(newPath.getPath().toString().indexOf(REPOSITORY) + 11); + newPolicyName = newPolicyName.replace(".xml", ""); + String version = newPolicyName.substring(newPolicyName.lastIndexOf(".") +1); + String policyName = newPolicyName.substring(0, newPolicyName.indexOf(".")); + newPolicyName = newPolicyName.replace(File.separator, "."); + //if the user leaves the name of the policy blank + if (newPolicyName == null) { + return; + }else{ + Path newPolicyPath = newPath.toPath(); + File dir = null; + File[] listOfFiles = null; + if(newPolicyName.contains(CONFIG)){ + LOG.debug("CONFIG_HOME: "+CONFIG_HOME); + dir=new File(CONFIG_HOME); + listOfFiles = dir.listFiles(); + }else if(newPolicyName.contains(ACTION)){ + LOG.debug("ACTION_HOME: "+ACTION_HOME); + dir=new File(ACTION_HOME); + listOfFiles = dir.listFiles(); + } + String indexValue = ""; + String orignalPolicyName = oldPath.getPath().toString().substring(oldPath.getPath().toString().indexOf(REPOSITORY) + 11); + orignalPolicyName = orignalPolicyName.replace(".xml", ""); + orignalPolicyName = orignalPolicyName.replace(File.separator, "."); + if(orignalPolicyName.contains("Config_Fault_")){ + indexValue = "Config_Fault_"; + } else if(orignalPolicyName.contains("Config_PM_")){ + indexValue = "Config_PM_"; + }else if(orignalPolicyName.contains("Config_FW")){ + indexValue = "Config_FW_"; + }else if(orignalPolicyName.contains("Config_BRMS_Param")){ + indexValue = "Config_BRMS_Param_"; + }else if(orignalPolicyName.contains("Config_BRMS_Raw")){ + indexValue = "Config_BRMS_Raw_"; + } else if(orignalPolicyName.contains("Config_MS")){ + indexValue = "Config_MS_"; + }else if(orignalPolicyName.contains(ACTION)){ + indexValue = ACTION; + }else if(orignalPolicyName.contains(DECISION)){ + indexValue = DECISION; + }else{ + indexValue = CONFIG; + } + File newConfigFile = null; + + //making changes to the xml file + if(indexValue.contains(CONFIG) || indexValue.contains(ACTION)){ + for (File file : listOfFiles) { + if (file.isFile()){ + String fileName=file.getName(); + if(fileName.contains(orignalPolicyName)){ + String newConfigFileName=fileName.replaceAll(orignalPolicyName,newPolicyName); + if(dir.toString().contains(File.separator)){ + newConfigFile=new File(dir.toString()+ File.separator +newConfigFileName); + } + try { + Files.copy(file.toPath(), newConfigFile.toPath()); + } catch (Exception e) { + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE +"Error while Cloning the config file" + e); + return; + } + } + } + } + XACMLPolicyWriterWithPapNotify.changeFileNameInXmlWhenRenamePolicy(newPolicyPath); + } + //set the clone policy name into policy version database table + PolicyVersion entityItem = new PolicyVersion(); + entityItem.setActiveVersion(Integer.parseInt(version)); + entityItem.setHigherVersion(Integer.parseInt(version)); + entityItem.setPolicyName(policyName); + entityItem.setCreatedBy(userId); + entityItem.setModifiedBy(userId); + PolicyController.SaveToPolicyVersion(entityItem); + + + new Thread(new Runnable() { + @Override + public void run() { + try { + ElkConnector.singleton.update(newPolicyPath.toFile()); + if (LOG.isInfoEnabled()) { + LOG.info("ELK cloning to " + newPolicyPath); + } + } catch (Exception e) { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Internal Error: Unsucessful clone: " + e.getMessage(), e); + } + } + }).start(); + + //send to pap + XACMLPolicyWriterWithPapNotify.notifyPapOfCreateUpdate(newPolicyPath.toAbsolutePath().toString()); + LOG.info("Cloned policy "+newPolicyName+" created successfully."); + return; + } + } + + //Delete Policy or Scope Functionality + private JSONObject delete(JSONObject params, HttpServletRequest request) throws ServletException { + try { + String userId = UserUtils.getUserIdFromCookie(request); + String deleteVersion = ""; + String path1 = params.getString("path"); + LOG.debug("delete {}" +path1); + if(params.has("deleteVersion")){ + deleteVersion = params.getString("deleteVersion"); + } + + this.repofilePath = new File(REPOSITORY_BASE_PATH, path1); + File policyFile = new File(REPOSITORY_BASE_PATH, path1); + if("ALL".equals(deleteVersion)){ + String removexmlExtension = policyFile.toString().substring(0, policyFile.toString().lastIndexOf(".")); + String removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf(".")); + String notificationName = removeVersion.substring(removeVersion.lastIndexOf(REPOSITORY)+11); + //Policy Notifcation + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(notificationName); + entity.setModifiedBy(userId); + controller.WatchPolicyFunction(entity, notificationName, "DeleteAll"); + File dirXML = new File(policyFile.getParent()); + File[] listOfXMLFiles = dirXML.listFiles(); + for (File file : listOfXMLFiles) { + //delete the xml files from Repository + if (file.isFile() && file.toString().contains(removeVersion)) { + if(XACMLPolicyWriterWithPapNotify.notifyPapOfDelete(file.toString())){ + LOG.info("Policy deleted from database. Continuing with file delete"); + } else { + LOG.error("Failed to delete Policy from database. Aborting file delete"); + } + //Elk Update + updateElkOnPolicyDelete(file); + + if (file.delete()) { + if (LOG.isDebugEnabled()) { + LOG.debug("Deleted file: " + file.toString()); + } + } else { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file in specified location: " + file.getAbsolutePath()); + } + + // Get tomcat home directory for deleting config data + String path = getParentPathSubScopeDir(); + path = path.replace('\\', '.'); + if(path.contains("/")){ + path = path.replace('/', '.'); + } + String fileName = FilenameUtils.removeExtension(file.getName()); + String removeVersionInFileName = fileName.substring(0, fileName.lastIndexOf(".")); + String fileLocation = null; + if (fileName != null && fileName.contains(CONFIG)) { + fileLocation = CONFIG_HOME; + } else if (fileName != null && fileName.contains(ACTION)) { + fileLocation = ACTION_HOME; + } + if (LOG.isDebugEnabled()) { + LOG.debug("Attempting to rename file from the location: "+ fileLocation); + } + if(!file.toString().contains(DECISION)){ + // Get the file from the saved location + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + + for (File file1 : listOfFiles) { + if (file1.isFile() && file1.getName().contains( path + removeVersionInFileName)) { + try { + if (file1.delete() == false) { + throw new Exception("No known error, Delete failed"); + } + } catch (Exception e) { + LOG.error("Failed to Delete file: "+ e.getLocalizedMessage()); + } + } + } + } + + //Delete the Policy from Database Policy Version table + String removeExtension = removeVersion.substring(removeVersion.indexOf(REPOSITORY)+11); + String policyVersionQuery = "delete from PolicyVersion where policy_name ='" +removeExtension.replace("\\", "\\\\")+"' and id >0"; + if(policyVersionQuery != null){ + PolicyController.updatePolicyVersion(policyVersionQuery); + } + } + } + //If Only Particular version to be deleted + }else if("CURRENT".equals(deleteVersion)){ + String removexmlExtension = policyFile.toString().substring(0, policyFile.toString().lastIndexOf(".")); + String getVersion = removexmlExtension.substring(removexmlExtension.indexOf(".")+1); + String removeVersion = removexmlExtension.substring(0, removexmlExtension.lastIndexOf(".")); + String notificationName = removeVersion.substring(removeVersion.lastIndexOf(REPOSITORY)+11); + //Policy Notifcation + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(notificationName); + entity.setActiveVersion(Integer.parseInt(getVersion)); + entity.setModifiedBy(userId); + controller.WatchPolicyFunction(entity, notificationName, "DeleteOne"); + if(XACMLPolicyWriterWithPapNotify.notifyPapOfDelete(policyFile.toString())){ + LOG.info("Policy deleted from database. Continuing with file delete"); + } else { + LOG.error("Failed to delete Policy from database. Aborting file delete"); + } + //Elk Update + updateElkOnPolicyDelete(policyFile); + + if (policyFile.delete()) { + LOG.debug("Deleted file: " + policyFile.toString()); + } else { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Cannot delete the policy file in specified location: " +policyFile.getAbsolutePath()); + } + + // Get tomcat home directory for storing action body config data + String path = getParentPathSubScopeDir(); + path = path.replace('\\', '.'); + if(path.contains("/")){ + path = path.replace('/', '.'); + LOG.info("print the path:" +path); + } + final String tempPath = path; + String fileName = FilenameUtils.removeExtension(policyFile.getName()); + String fileLocation = null; + if (fileName != null && fileName.contains(CONFIG)) { + fileLocation = CONFIG_HOME; + } else if (fileName != null && fileName.contains(ACTION)) { + fileLocation = ACTION_HOME; + } + if (LOG.isDebugEnabled()) { + LOG.debug("Attempting to delete file from the location: "+ fileLocation); + } + if(!policyFile.toString().contains(DECISION)){ + // Get the file from the saved location + File dir = new File(fileLocation); + File[] listOfFiles = dir.listFiles(); + + for (File file : listOfFiles) { + if (file.isFile() && file.toString().contains( tempPath + fileName)) { + try { + if (file.delete() == false) { + throw new Exception("No known error, Delete failed"); + } + } catch (Exception e) { + LOG.error("Failed to Delete file: "+ e.getLocalizedMessage()); + } + } + } + } + //Delete the Policy from Database and set Active Version based on the deleted file. + int highestVersion = 0; + String removeExtension = removeVersion.substring(removeVersion.indexOf(REPOSITORY)+11); + PolicyVersion policyVersionEntity = PolicyController.getPolicyEntityFromPolicyVersion(removeExtension); + if(policyVersionEntity != null){ + highestVersion = policyVersionEntity.getHigherVersion(); + } + int i =0; + int version = Integer.parseInt(getVersion); + if(version == highestVersion){ + for(i = highestVersion; i >= 1 ; i--){ + highestVersion = highestVersion-1; + path = removeVersion + "."+ highestVersion +".xml"; + File file = new File(path); + if(file.exists()){ + break; + } + } + } + String updatequery = "update PolicyVersion set active_version='"+highestVersion+"' , highest_version='"+highestVersion+"' where policy_name ='" +removeExtension.replace("\\", "\\\\")+"'"; + PolicyController.updatePolicyVersion(updatequery); + }else{ + String scopeName = policyFile.getAbsolutePath().substring(policyFile.getAbsolutePath().indexOf(REPOSITORY)+11); + String policyVersionQuery = "delete PolicyVersion where POLICY_NAME like '"+scopeName.replace("\\", "\\\\")+"%' and id >0"; + String policyScopeQuery = "delete PolicyEditorScopes where SCOPENAME like '"+scopeName.replace("\\", "\\\\")+"%' and id >0"; + PolicyController.updatePolicyVersion(policyVersionQuery); + PolicyController.updatePolicyScopeEditorWithQuery(policyScopeQuery); + delete(policyFile); + //Policy Notifcation + PolicyController controller = new PolicyController(); + PolicyVersion entity = new PolicyVersion(); + entity.setPolicyName(scopeName); + entity.setModifiedBy(userId); + controller.WatchPolicyFunction(entity, scopeName, "DeleteScope"); + } + return success(); + } catch (Exception e) { + LOG.error("delete", e); + return error(e.getMessage()); + } + } + + //Notify ELK on File Delete + private void updateElkOnPolicyDelete(File file){ + try { + ElkConnector.singleton.delete(file); + } catch (Exception e) { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Cannot delete: " + file.getName() + + " at " + file.getAbsolutePath() + ": " + e.getMessage(), e); + } + } + //Deletes Files when Scope is Selected to delete + public void delete(File file) throws IOException{ + if(file.isDirectory()){ + //directory is empty, then delete it + if(file.list().length==0){ + file.delete(); + }else{ + //list all the directory contents + String[] files = file.list(); + for (String temp : files) { + //construct the file structure + File fileDelete = new File(file, temp); + //delete from Elk first + if(fileDelete.getAbsolutePath().toString().endsWith(".xml")){ + try { + String deleteFile= fileDelete.getAbsoluteFile().toString().substring(fileDelete.getAbsoluteFile().toString().indexOf("workspace")); + File deletePath= new File(deleteFile); + LOG.debug("Search:"+deletePath); + ElkConnector.singleton.delete(deletePath); + } catch (Exception e) { + LOG.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + ": Cannot delete: " + fileDelete.getAbsoluteFile().getName() + + " at " + fileDelete.getAbsoluteFile().getAbsolutePath() + ": " +e.getMessage(), e); + } + } + + //recursive delete + delete(fileDelete); + + //Delete the Configuration files from Config and Action Home Location + String fileLocation = null; + String policyName = fileDelete.toString().substring(fileDelete.toString().indexOf(REPOSITORY)+11, fileDelete.toString().lastIndexOf(".")); + if(policyName.contains(CONFIG)){ + fileLocation = PolicyController.getConfigHome(); + } + if(policyName.contains(ACTION)){ + fileLocation = PolicyController.getActionHome(); + } + if(policyName.contains(File.separator)){ + policyName = policyName.replace(File.separator, "."); + } + if(!fileDelete.toString().contains(DECISION) && fileLocation != null){ + // Get the file from the saved location and delete + File dir = new File(fileLocation); + FileFilter fileFilter = new WildcardFileFilter(policyName + ".*"); + File[] configFiles = (dir).listFiles(fileFilter); + if(configFiles.length > 0){ + configFiles[0].delete(); + } + } + //Notify the PAP and Elk database for deleting the Policies Under Scopes + if(fileDelete.getAbsolutePath().toString().endsWith(".xml")){ + if(!XACMLPolicyWriterWithPapNotify.notifyPapOfDelete(fileDelete.getAbsolutePath().toString())){ + LOG.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Could not delete the policy from the database: "+ + fileDelete.getAbsolutePath().toString()); + throw new IOException("Could not delete the policy from the database: "+ + fileDelete.getAbsolutePath().toString()); + } + } + } + //check the directory again, if empty then delete it + if(file.list().length==0){ + file.delete(); + } + } + }else{ + //if file, then delete it + file.delete(); + } + } + + //Get the Parent Scope of File + protected String getParentPathSubScopeDir() { + String domain1 = null; + final Path gitPath = PolicyController.getGitPath(); + String policyDir = this.repofilePath.getAbsolutePath(); + int startIndex = policyDir.indexOf(gitPath.toString()) + gitPath.toString().length() + 1; + policyDir = policyDir.substring(startIndex, policyDir.length()); + if(policyDir.contains(CONFIG)){ + domain1 = policyDir.substring(0,policyDir.indexOf(CONFIG)); + }else if(policyDir.contains(ACTION)){ + domain1 = policyDir.substring(0,policyDir.indexOf(ACTION)); + }else{ + domain1 = policyDir.substring(0,policyDir.indexOf(DECISION)); + } + LOG.info("print the main domain value"+policyDir); + return domain1; + } + + //Edit the Policy + private JSONObject editFile(JSONObject params) throws ServletException { + // get content + try { + String mode = params.getString("mode"); + String path = params.getString("path"); + LOG.debug("editFile path: {}"+ path); + + File policyFile = new File(REPOSITORY_BASE_PATH, path); + + Object policy = XACMLPolicyScanner.readPolicy(new FileInputStream(policyFile)); + Path fullPath = Paths.get(policyFile.getAbsolutePath(), new String[0]); + PolicyAdapter policyAdapter = new PolicyAdapter(); + policyAdapter.setData(policy); + String dirPath = fullPath.getParent().toString().substring(fullPath.getParent().toString().lastIndexOf(REPOSITORY)+11); + policyAdapter.setDirPath(dirPath); + policyAdapter.setParentPath(fullPath.getParent()); + + if("viewPolicy".equalsIgnoreCase(mode)){ + policyAdapter.setReadOnly(true); + policyAdapter.setEditPolicy(false); + }else{ + policyAdapter.setReadOnly(false); + policyAdapter.setEditPolicy(true); + } + + policyAdapter.setPolicyData(policy); + policyAdapter.setPolicyName(FilenameUtils.removeExtension(policyFile.getName())); + + String policyNameValue = null ; + String configPolicyName = null ; + 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 = "DCAE 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); + } + if("Decision".equalsIgnoreCase(policyAdapter.getPolicyType())){ + DecisionPolicyController decisionController = new DecisionPolicyController(); + decisionController.PrePopulateDecisionPolicyData(policyAdapter); + } + if("Config".equalsIgnoreCase(policyAdapter.getPolicyType())){ + if("Base".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreatePolicyController baseController = new CreatePolicyController(); + baseController.PrePopulateBaseConfigPolicyData(policyAdapter); + } + else if("BRMS_Raw".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateBRMSRawController brmsController = new CreateBRMSRawController(); + brmsController.PrePopulateBRMSRawPolicyData(policyAdapter); + } + else if("BRMS_Param".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateBRMSParamController paramController = new CreateBRMSParamController(); + paramController.PrePopulateBRMSParamPolicyData(policyAdapter); + } + else if("ClosedLoop_Fault".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateClosedLoopFaultController newFaultTemplate = new CreateClosedLoopFaultController(); + newFaultTemplate.PrePopulateClosedLoopFaultPolicyData(policyAdapter); + } + else if("ClosedLoop_PM".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateClosedLoopPMController pmController = new CreateClosedLoopPMController(); + pmController.PrePopulateClosedLoopPMPolicyData(policyAdapter); + } + else if("DCAE Micro Service".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateDcaeMicroServiceController msController = new CreateDcaeMicroServiceController(); + msController.PrePopulateDCAEMSPolicyData(policyAdapter); + } + else if("Firewall Config".equalsIgnoreCase(policyAdapter.getConfigPolicyType())){ + CreateFirewallController firewallController = new CreateFirewallController(); + firewallController.PrePopulateFWPolicyData(policyAdapter); + } + } + + + 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) { + LOG.error("editFile", e); + return error(e.getMessage()); + } + } + + //Add Scopes + private JSONObject addFolder(JSONObject params, HttpServletRequest request) throws ServletException { + String name = ""; + + try { + String userId = UserUtils.getUserIdFromCookie(request); + 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"); + LOG.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Exception Occured While Adding Scope"+e); + } + + + LOG.debug("addFolder path: {} name: {}" + path +name); + File newDir = new File(REPOSITORY_BASE_PATH, name); + if(!newDir.exists()){ + if (!newDir.mkdir()) { + throw new Exception("Can't create directory: " + newDir.getAbsolutePath()); + } + UserInfo userInfo = new UserInfo(); + userInfo.setUserLoginId(userId); + PolicyEditorScopes newScope = new PolicyEditorScopes(); + String scopeName = null; + if(name.startsWith(File.separator)){ + scopeName = name.substring(1); + }else{ + scopeName = name; + } + newScope.setScopeName(scopeName); + newScope.setUserCreatedBy(userInfo); + newScope.setUserModifiedBy(userInfo); + PolicyController.SavePolicyScope(newScope); + }else{ + return error("Scope Already Exists"); + } + + return success(); + } catch (Exception e) { + LOG.error("addFolder", e); + return error(e.getMessage()); + } + } + + //Return Error Object + private JSONObject error(String msg) throws ServletException { + try { + JSONObject result = new JSONObject(); + result.put("success", false); + result.put("error", msg); + return new JSONObject().put(RESULT, result); + } catch (JSONException e) { + throw new ServletException(e); + } + } + + //Return Success Object + private JSONObject success() throws ServletException { + try { + JSONObject result = new JSONObject(); + result.put("success", true); + result.put("error", (Object) null); + return new JSONObject().put(RESULT, result); + } catch (JSONException e) { + throw new ServletException(e); + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java new file mode 100644 index 000000000..186adfa29 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/PolicyNotificationMail.java @@ -0,0 +1,140 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + +/* + * + * + * + * */ +import java.io.UnsupportedEncodingException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Properties; + +import javax.mail.MessagingException; +import javax.mail.internet.InternetAddress; +import javax.mail.internet.MimeMessage; + +import org.openecomp.policy.controller.PolicyController; +import org.openecomp.policy.dao.WatchPolicyNotificationDao; +import org.openecomp.policy.rest.jpa.PolicyVersion; +import org.openecomp.policy.rest.jpa.WatchPolicyNotificationTable; +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; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; + +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +@Configurable +public class PolicyNotificationMail{ + private static Logger logger = FlexLogger.getLogger(PolicyNotificationMail.class); + + @Bean + public JavaMailSenderImpl javaMailSenderImpl(){ + JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); + mailSender.setHost(PolicyController.smtpHost); + mailSender.setPort(Integer.parseInt(PolicyController.smtpPort)); + mailSender.setUsername(PolicyController.smtpUsername); + mailSender.setPassword(PolicyController.smtpPassword); + Properties prop = mailSender.getJavaMailProperties(); + prop.put("mail.transport.protocol", "smtp"); + prop.put("mail.smtp.auth", "true"); + prop.put("mail.smtp.starttls.enable", "true"); + prop.put("mail.debug", "true"); + return mailSender; + } + + @SuppressWarnings("resource") + public void sendMail(PolicyVersion entityItem, String policyName, String mode, WatchPolicyNotificationDao policyNotificationDao) throws MessagingException { + String from = PolicyController.smtpUsername; + String to = ""; + String subject = ""; + String message = ""; + DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); + Date date = new Date(); + if(mode.equalsIgnoreCase("EditPolicy")){ + subject = "Policy has been Updated : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Updated" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Modified By : " +entityItem.getModifiedBy() + '\n' + "Modified Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("Rename")){ + subject = "Policy has been Renamed : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Renamed" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Renamed By : " +entityItem.getModifiedBy() + '\n' + "Renamed Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("DeleteAll")){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted with All Versions" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("DeleteOne")){ + subject = "Policy has been Deleted : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' +"Policy Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("DeleteScope")){ + subject = "Scope has been Deleted : "+entityItem.getPolicyName(); + message = "The Scope Which you are watching in " + PolicyController.smtpApplicationName + " has been Deleted" + '\n' + '\n' + '\n'+ "Scope + Scope Name : " + policyName + '\n' + + '\n' + '\n' + "Deleted By : " +entityItem.getModifiedBy() + '\n' + "Deleted Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("SwitchVersion")){ + subject = "Policy has been SwitchedVersion : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been SwitchedVersion" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Switched By : " +entityItem.getModifiedBy() + '\n' + "Switched Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + if(mode.equalsIgnoreCase("Move")){ + subject = "Policy has been Moved to Other Scope : "+entityItem.getPolicyName(); + message = "The Policy Which you are watching in " + PolicyController.smtpApplicationName + " has been Moved to Other Scope" + '\n' + '\n' + '\n'+ "Scope + Policy Name : " + policyName + '\n' + "Active Version : " +entityItem.getActiveVersion() + + '\n' + '\n' + "Moved By : " +entityItem.getModifiedBy() + '\n' + "Moved Time : " +dateFormat.format(date) + '\n' + '\n' + '\n' + '\n' + "Policy Notification System (please don't respond to this email)"; + } + String policyFileName = entityItem.getPolicyName(); + List watchList = policyNotificationDao.getListDataByPolicyName(policyFileName); + if(watchList.size() > 0){ + for(WatchPolicyNotificationTable list : watchList){ + to = list.getLoginIds()+"@"+PolicyController.smtpEmailExtension; + to = to.trim(); + AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); + ctx.register(PolicyNotificationMail.class); + ctx.refresh(); + JavaMailSenderImpl mailSender = ctx.getBean(JavaMailSenderImpl.class); + MimeMessage mimeMessage = mailSender.createMimeMessage(); + MimeMessageHelper mailMsg = new MimeMessageHelper(mimeMessage); + try { + mailMsg.setFrom(new InternetAddress(from, "Policy Notification System")); + } catch (UnsupportedEncodingException e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW+"Exception Occured in Policy Notification" +e); + } + mailMsg.setTo(to); + mailMsg.setSubject(subject); + mailMsg.setText(message); + mailSender.send(mimeMessage); + } + } + } +} diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java new file mode 100644 index 000000000..ecb610264 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/RESTfulPAPEngine.java @@ -0,0 +1,732 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + + + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.URL; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +import org.apache.commons.io.IOUtils; +import org.openecomp.policy.adapter.PolicyAdapter; +import org.openecomp.policy.rest.XACMLRestProperties; + +import org.openecomp.policy.xacml.api.XACMLErrorConstants; +import org.openecomp.policy.xacml.api.pap.EcompPDP; +import org.openecomp.policy.xacml.api.pap.EcompPDPGroup; +import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; +import org.openecomp.policy.xacml.std.pap.StdPAPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDP; +import org.openecomp.policy.xacml.std.pap.StdPDPGroup; +import org.openecomp.policy.xacml.std.pap.StdPDPItemSetChangeNotifier; +import org.openecomp.policy.xacml.std.pap.StdPDPPolicy; +import org.openecomp.policy.xacml.std.pap.StdPDPStatus; +import com.att.research.xacml.api.pap.PAPEngine; +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.PDP; +//import com.att.research.xacml.api.pap.PDPGroup; +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.introspect.VisibilityChecker; +import com.fasterxml.jackson.databind.type.CollectionType; +import org.openecomp.policy.common.logging.flexlogger.FlexLogger; +import org.openecomp.policy.common.logging.flexlogger.Logger; + +/** + * Implementation of the PAPEngine interface that communicates with a PAP engine in a remote servlet + * through a RESTful interface + * + * + */ +public class RESTfulPAPEngine extends StdPDPItemSetChangeNotifier implements PAPPolicyEngine { + private static final Logger logger = FlexLogger.getLogger(RESTfulPAPEngine.class); + + // + // URL of the PAP Servlet that this Admin Console talks to + // + private String papServletURLString; + + /** + * Set up link with PAP Servlet and get our initial set of Groups + * @throws Exception + */ + public RESTfulPAPEngine (String myURLString) throws PAPException, IOException { + // + // Get our URL to the PAP servlet + // + this.papServletURLString = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_URL); + if (this.papServletURLString == null || this.papServletURLString.length() == 0) { + String message = "The property 'POLICYENGINE_ADMIN_ACTIVE' was not set during installation. Admin Console cannot call PAP."; + logger.error(message); + throw new PAPException(message); + } + + // + // register this Admin Console with the PAP Servlet to get updates + // + Object newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); + if (newURL != null) { + // assume this was a re-direct and try again + logger.warn("Redirecting to '" + newURL + "'"); + this.papServletURLString = (String)newURL; + newURL = sendToPAP("PUT", null, null, null, "adminConsoleURL=" + myURLString); + if (newURL != null) { + logger.error("Failed to redirect to " + this.papServletURLString); + throw new PAPException("Failed to register with PAP"); + } + } + } + + + // + // High-level commands used by the Admin Console code through the PAPEngine Interface + // + + @Override + public EcompPDPGroup getDefaultGroup() throws PAPException { + EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "default="); + return newGroup; + } + + @Override + public void SetDefaultGroup(EcompPDPGroup group) throws PAPException { + sendToPAP("POST", null, null, null, "groupId=" + group.getId(), "default=true"); + } + + @SuppressWarnings("unchecked") + @Override + public Set getEcompPDPGroups() throws PAPException { + Set newGroupSet; + newGroupSet = (Set) this.sendToPAP("GET", null, Set.class, StdPDPGroup.class, "groupId="); + return Collections.unmodifiableSet(newGroupSet); + } + + + @Override + public EcompPDPGroup getGroup(String id) throws PAPException { + EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=" + id); + return newGroup; + } + + @Override + public void newGroup(String name, String description) + throws PAPException, NullPointerException { + String escapedName = null; + String escapedDescription = null; + try { + escapedName = URLEncoder.encode(name, "UTF-8"); + escapedDescription = URLEncoder.encode(description, "UTF-8"); + } catch (UnsupportedEncodingException e) { + throw new PAPException("Unable to send name or description to PAP: " + e.getMessage()); + } + + this.sendToPAP("POST", null, null, null, "groupId=", "groupName="+escapedName, "groupDescription=" + escapedDescription); + } + + + /** + * Update the configuration on the PAP for a single Group. + * + * @param group + * @return + * @throws PAPException + */ + public void updateGroup(EcompPDPGroup group) throws PAPException { + + try { + + // + // ASSUME that all of the policies mentioned in this group are already located in the correct directory on the PAP! + // + // Whenever a Policy is added to the group, that file must be automatically copied to the PAP from the Workspace. + // + + +// // Copy all policies from the local machine's workspace to the PAP's PDPGroup directory. +// // This is not efficient since most of the policies will already exist there. +// // However, the policy files are (probably!) not too huge, and this is a good way to ensure that any corrupted files on the PAP get refreshed. +// + + // now update the group object on the PAP + + sendToPAP("PUT", group, null, null, "groupId=" + group.getId()); + } catch (Exception e) { + String message = "Unable to PUT policy '" + group.getId() + "', e:" + e; + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + @Override + public void removeGroup(EcompPDPGroup group, EcompPDPGroup newGroup) + throws PAPException, NullPointerException { + String moveToGroupString = null; + if (newGroup != null) { + moveToGroupString = "movePDPsToGroupId=" + newGroup.getId(); + } + sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), moveToGroupString); + } + + @Override + public EcompPDPGroup getPDPGroup(EcompPDP pdp) throws PAPException { + return getPDPGroup(pdp.getId()); + } + + + public EcompPDPGroup getPDPGroup(String pdpId) throws PAPException { + EcompPDPGroup newGroup = (EcompPDPGroup)sendToPAP("GET", null, null, StdPDPGroup.class, "groupId=", "pdpId=" + pdpId, "getPDPGroup="); + return newGroup; + } + + @Override + public EcompPDP getPDP(String pdpId) throws PAPException { + EcompPDP newPDP = (EcompPDP)sendToPAP("GET", null, null, StdPDP.class, "groupId=", "pdpId=" + pdpId); + return newPDP; + } + + @Override + public void newPDP(String id, EcompPDPGroup group, String name, String description, int jmxport) throws PAPException, + NullPointerException { + StdPDP newPDP = new StdPDP(id, name, description, jmxport); + sendToPAP("PUT", newPDP, null, null, "groupId=" + group.getId(), "pdpId=" + id); + return; + } + + @Override + public void movePDP(EcompPDP pdp, EcompPDPGroup newGroup) throws PAPException { + sendToPAP("POST", null, null, null, "groupId=" + newGroup.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void updatePDP(EcompPDP pdp) throws PAPException { + EcompPDPGroup group = getPDPGroup(pdp); + sendToPAP("PUT", pdp, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId()); + return; + } + + @Override + public void removePDP(EcompPDP pdp) throws PAPException { + EcompPDPGroup group = getPDPGroup(pdp); + sendToPAP("DELETE", null, null, null, "groupId=" + group.getId(), "pdpId=" + pdp.getId()); + return; + } + + //Validate the Policy Data + public boolean validatePolicyRequest(PolicyAdapter policyAdapter, String policyType) throws PAPException { + Boolean isValidData = false; +/* StdPAPPolicy newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getConfigName(), + policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getConfigBodyData(), policyAdapter.getPolicyID(), policyAdapter.getRuleID(), + policyAdapter.getRuleCombiningAlgId(), policyAdapter.getParentPath().toString(), policyAdapter.getGitPath().toString(), policyAdapter.getConfigType(), policyAdapter.isEditPolicy()); + */ + + 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; + } + + //create a new policy + @SuppressWarnings("unchecked") + public Map createPolicyRequest(PolicyAdapter policyAdapter) throws PAPException { + Map successMap = new HashMap(); + StdPAPPolicy newPAPPolicy = null; + + if (policyAdapter.getPolicyType().equalsIgnoreCase("Config")) { + + if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) { + + //create StdPAPPolicy object for Config Firewall Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getJsonBody(), + policyAdapter.getHighestVersion() ,policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Raw")) { + + //create StdPAPPolicy object for BRMS_Raw Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getRiskLevel(), + policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Param")) { + + //create StdPAPPolicy object for BRMS_Param Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getBRMSParamBody(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + + else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Base")) { + + //create StdPAPPolicy object for Config Base Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getConfigName(), policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getConfigType(), + policyAdapter.getConfigBodyData(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) { + + //create StdPAPPolicy object for CloseLoop Fault Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getJsonBody(), policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), null, policyAdapter.isEditPolicy(), + policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) { + + //create StdPAPPolicy object for CloseLoop PM Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getJsonBody(), policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), policyAdapter.getServiceType(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), + policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) { + + //create StdPAPPolicy object for DCAE Micro Service Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getConfigName(), policyAdapter.getServiceType(), policyAdapter.getUuid(), policyAdapter.getLocation(), + policyAdapter.getJsonBody(), policyAdapter.getPriority(), null, policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), + policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Action")) { + + //create StdPAPPolicy object for Action Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getDynamicRuleAlgorithmLabels(), policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), + policyAdapter.getDynamicRuleAlgorithmField2(), policyAdapter.getActionPerformer(), policyAdapter.getActionAttribute(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion()); + + } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) { + + //create StdPAPPolicy object for Decision Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getRuleProvider(), + policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getDynamicSettingsMap(), policyAdapter.getDynamicRuleAlgorithmLabels(), + policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), policyAdapter.getDynamicRuleAlgorithmField2(), + policyAdapter.getDropDownMap(), policyAdapter.getDynamicVariableList(), policyAdapter.getDataTypeList(), policyAdapter.isEditPolicy(), + policyAdapter.getDomainDir(), policyAdapter.getHighestVersion()); + + } + + //send JSON object to PAP + successMap = (Map) sendToPAP("PUT", newPAPPolicy, null, null, "operation=create", "apiflag=admin", "policyType=" + policyAdapter.getPolicyType()); + return successMap; + + + } + + //update an existing policy + @SuppressWarnings("unchecked") + public Map updatePolicyRequest(PolicyAdapter policyAdapter) throws PAPException { + Map successMap = new HashMap(); + StdPAPPolicy newPAPPolicy = null; + + if (policyAdapter.getPolicyType().equalsIgnoreCase("Config")) { + + if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Firewall Config")) { + + //create StdPAPPolicy object for Firewall Config Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getConfigName(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getPolicyID(), + policyAdapter.getRuleID(), policyAdapter.getVersion(), policyAdapter.getJsonBody(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), + policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Raw")) { + //create StdPAPPolicy object for BRMS_Raw Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getRiskLevel(), + policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("BRMS_Param")) { + //create StdPAPPolicy object for BRMS_Raw Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getConfigName(), policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getHighestVersion(),policyAdapter.getEcompName(),policyAdapter.getConfigBodyData(),policyAdapter.getBRMSParamBody(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("Base")) { + + //create StdPAPPolicy object for Config Base Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getConfigName(), + policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getConfigBodyData(), policyAdapter.getPolicyID(), policyAdapter.getRuleID(), + policyAdapter.getConfigType(), policyAdapter.isEditPolicy(), policyAdapter.getVersion(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), + policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_Fault")) { + + //create StdPAPPolicy object for CloseLoop Fault Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getJsonBody(), policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), null, policyAdapter.isEditPolicy(), + policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(), + policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("ClosedLoop_PM")) { + + //create StdPAPPolicy object for CloseLoop PM Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getJsonBody(), policyAdapter.isDraft(), policyAdapter.getOldPolicyFileName(), policyAdapter.getServiceType(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(),policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), + policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + }else if (policyAdapter.getConfigPolicyType().equalsIgnoreCase("DCAE Micro Service")) { + + //create StdPAPPolicy object for DCAE Micro Service Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getConfigPolicyType(), policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), + policyAdapter.getEcompName(), policyAdapter.getConfigName(), policyAdapter.getServiceType(), policyAdapter.getUuid(), policyAdapter.getLocation(), + policyAdapter.getJsonBody(), policyAdapter.getPriority(), null, policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion(), + policyAdapter.getRiskLevel(), policyAdapter.getRiskType(), policyAdapter.getGuard(),policyAdapter.getTtlDate()); + + } + } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Action")) { + + //create StdPAPPolicy object for Action Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getDynamicFieldConfigAttributes(), + policyAdapter.getDynamicRuleAlgorithmLabels(), policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), + policyAdapter.getDynamicRuleAlgorithmField2(), policyAdapter.getActionPerformer(), policyAdapter.getActionAttribute(), + policyAdapter.isEditPolicy(), policyAdapter.getDomainDir(), policyAdapter.getHighestVersion()); + + } else if (policyAdapter.getPolicyType().equalsIgnoreCase("Decision")) { + + //create StdPAPPolicy object for Decision Policy + newPAPPolicy = new StdPAPPolicy(policyAdapter.getPolicyName(), policyAdapter.getPolicyDescription(), policyAdapter.getEcompName(), policyAdapter.getRuleProvider(), + policyAdapter.getDynamicFieldConfigAttributes(), policyAdapter.getDynamicSettingsMap(), policyAdapter.getDynamicRuleAlgorithmLabels(), + policyAdapter.getDynamicRuleAlgorithmCombo(), policyAdapter.getDynamicRuleAlgorithmField1(), policyAdapter.getDynamicRuleAlgorithmField2(), + policyAdapter.getDropDownMap(), policyAdapter.getDynamicVariableList(), policyAdapter.getDataTypeList(), policyAdapter.isEditPolicy(), + policyAdapter.getDomainDir(), policyAdapter.getHighestVersion()); + + } + + //send JSON object to PAP + successMap = (Map) sendToPAP("PUT", newPAPPolicy, null, null, "operation=update", "apiflag=admin", "policyType=" + policyAdapter.getPolicyType()); + return successMap; + } + + @Override + public void publishPolicy(String id, String name, boolean isRoot, + InputStream policy, EcompPDPGroup group) throws PAPException { + + + // copy the (one) file into the target directory on the PAP servlet + copyFile(id, group, policy); + + // adjust the local copy of the group to include the new policy + PDPPolicy pdpPolicy = new StdPDPPolicy(id, isRoot, name); + group.getPolicies().add(pdpPolicy); + + // tell the PAP servlet to include the policy in the configuration + updateGroup(group); + + return; + } + + + + /** + * Copy a single Policy file from the input stream to the PAP Servlet. + * Either this works (silently) or it throws an exception. + * + * @param policyId + * @param group + * @param policy + * @return + * @throws PAPException + */ + public void copyFile(String policyId, EcompPDPGroup group, InputStream policy) throws PAPException { + // send the policy file to the PAP Servlet + try { + sendToPAP("POST", policy, null, null, "groupId=" + group.getId(), "policyId="+policyId); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policyId + "', e:" + e; + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + @Override + public void copyPolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException { + if (policy == null || group == null) { + throw new PAPException("Null input policy="+policy+" group="+group); + } + try (InputStream is = new FileInputStream(new File(policy.getLocation())) ) { + copyFile(policy.getId(), group, is ); + } catch (Exception e) { + String message = "Unable to PUT policy '" + policy.getId() + "', e:" + e; + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + message, e); + throw new PAPException(message); + } + } + + + + + @Override + public void removePolicy(PDPPolicy policy, EcompPDPGroup group) throws PAPException { + throw new PAPException("NOT IMPLEMENTED"); + + } + + + + /** + * Special operation - Similar to the normal PAP operations but this one contacts the PDP directly + * to get detailed status info. + * + * @param pdp + * @return + * @throws PAPException + */ + + public PDPStatus getStatus(EcompPDP pdp) throws PAPException { + StdPDPStatus status = (StdPDPStatus)sendToPAP("GET", pdp, null, StdPDPStatus.class); + return status; + } + + + + + // + // Internal Operations called by the PAPEngine Interface methods + // + + /** + * Send a request to the PAP Servlet and get the response. + * + * The content is either an InputStream to be copied to the Request OutputStream + * OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream. + * + * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller. + * + * @param method + * @param content - EITHER an InputStream OR an Object to be encoded in JSON + * @param collectionTypeClass + * @param responseContentClass + * @param parameters + * @return + * @throws Exception + */ + private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters ) throws PAPException { + HttpURLConnection connection = null; + String papID = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + logger.info("User Id is " + papID); + String papPass = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_PASS); + logger.info("Pass is: " + papPass); + Base64.Encoder encoder = Base64.getEncoder(); + String encoding = encoder.encodeToString((papID+":"+papPass).getBytes(StandardCharsets.UTF_8)); + logger.info("Encoding for the PAP is: " + encoding); + try { + String fullURL = papServletURLString; + if (parameters != null && parameters.length > 0) { + String queryString = ""; + for (String p : parameters) { + queryString += "&" + p; + } + fullURL += "?" + queryString.substring(1); + } + + // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP + if (method.equals("GET") && (content instanceof EcompPDP) && responseContentClass == StdPDPStatus.class) { + // Adjust the url and properties appropriately + String pdpID =((EcompPDP)content).getId(); + fullURL = pdpID + "?type=Status"; + content = null; + if(CheckPDP.validateID(pdpID)){ + encoding = CheckPDP.getEncoding(pdpID); + } + } + + + URL url = new URL(fullURL); + + // + // Open up the connection + // + connection = (HttpURLConnection)url.openConnection(); + // + // Setup our method and headers + // + connection.setRequestMethod(method); +// connection.setRequestProperty("Accept", "text/x-java-properties"); +// connection.setRequestProperty("Content-Type", "text/x-java-properties"); + connection.setUseCaches(false); + // + // Adding this in. It seems the HttpUrlConnection class does NOT + // properly forward our headers for POST re-direction. It does so + // for a GET re-direction. + // + // So we need to handle this ourselves. + // + connection.setInstanceFollowRedirects(false); + connection.setRequestProperty("Authorization", "Basic " + encoding); + connection.setDoOutput(true); + connection.setDoInput(true); + + if (content != null) { + if (content instanceof InputStream) { + try { + // + // Send our current policy configuration + // + try (OutputStream os = connection.getOutputStream()) { + int count = IOUtils.copy((InputStream)content, os); + if (logger.isDebugEnabled()) { + logger.debug("copied to output, bytes="+count); + } + } + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to write content in '" + method + "'", e); + throw e; + } + } else { + // The content is an object to be encoded in JSON + ObjectMapper mapper = new ObjectMapper(); + mapper.writeValue(connection.getOutputStream(), content); + } + } + // + // Do the connect + // + connection.connect(); + if (connection.getResponseCode() == 204) { + logger.info("Success - no content."); + return null; + } else if (connection.getResponseCode() == 200) { + logger.info("Success. We have a return object."); + String isValidData = connection.getHeaderField("isValidData"); + String isSuccess = connection.getHeaderField("successMapKey"); + Map successMap = new HashMap(); + if (isValidData != null && isValidData.equalsIgnoreCase("true")){ + logger.info("Policy Data is valid."); + return true; + } else if (isValidData != null && isValidData.equalsIgnoreCase("false")) { + logger.info("Policy Data is invalid."); + return false; + } else if (isSuccess != null && isSuccess.equalsIgnoreCase("success")) { + logger.info("Policy Created Successfully!" ); + String finalPolicyPath = connection.getHeaderField("finalPolicyPath"); + successMap.put("success", finalPolicyPath); + return successMap; + } else if (isSuccess != null && isSuccess.equalsIgnoreCase("error")) { + logger.info("There was an error while creating the policy!"); + successMap.put("error", "error"); + return successMap; + } else { + // get the response content into a String + String json = null; + // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) + java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); + scanner.useDelimiter("\\A"); + json = scanner.hasNext() ? scanner.next() : ""; + scanner.close(); + logger.info("JSON response from PAP: " + json); + + // convert Object sent as JSON into local object + ObjectMapper mapper = new ObjectMapper(); + mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); + if (collectionTypeClass != null) { + // collection of objects expected + final CollectionType javaType = + mapper.getTypeFactory().constructCollectionType(collectionTypeClass, responseContentClass); + + Object objectFromJSON = mapper.readValue(json, javaType); + return objectFromJSON; + } else { + // single value object expected + Object objectFromJSON = mapper.readValue(json, responseContentClass); + return objectFromJSON; + } + } + + } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { + // redirection + String newURL = connection.getHeaderField("Location"); + if (newURL == null) { + logger.error("No Location header to redirect to when response code="+connection.getResponseCode()); + throw new IOException("No redirect Location header when response code="+connection.getResponseCode()); + } + int qIndex = newURL.indexOf("?"); + if (qIndex > 0) { + newURL = newURL.substring(0, qIndex); + } + logger.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); + return newURL; + } else { + logger.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); + throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); + } + + } catch (Exception e) { + logger.error(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "HTTP Request/Response to PAP: " + e,e); + throw new PAPException("Request/Response threw :" + e); + } finally { + // cleanup the connection + if (connection != null) { + try { + // For some reason trying to get the inputStream from the connection + // throws an exception rather than returning null when the InputStream does not exist. + InputStream is = null; + try { + is = connection.getInputStream(); + } catch (Exception e1) { + // ignore this + } + if (is != null) { + is.close(); + } + + } catch (IOException ex) { + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to close connection: " + ex, ex); + } + connection.disconnect(); + } + } + } + +} + + diff --git a/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/XacmlAdminUI.java b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/XacmlAdminUI.java new file mode 100644 index 000000000..aec8a0ac1 --- /dev/null +++ b/ecomp-sdk-app/src/main/java/org/openecomp/policy/admin/XacmlAdminUI.java @@ -0,0 +1,266 @@ +/*- + * ============LICENSE_START======================================================= + * ECOMP Policy Engine + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.policy.admin; + + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; + +import javax.servlet.ServletConfig; +import javax.servlet.ServletException; +import javax.servlet.annotation.WebInitParam; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServlet; + + +import org.eclipse.jgit.api.Git; +import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Repository; +import org.eclipse.jgit.lib.StoredConfig; +import org.eclipse.jgit.storage.file.FileRepositoryBuilder; +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.openecomp.policy.rest.XACMLRest; +import org.openecomp.policy.rest.XACMLRestProperties; +import org.openecomp.policy.rest.dao.UserInfoDao; +import org.openecomp.policy.rest.jpa.UserInfo; +import org.openecomp.policy.rest.util.Webapps; +import org.openecomp.policy.xacml.api.pap.PAPPolicyEngine; +import org.springframework.beans.factory.annotation.Autowired; + +import com.att.research.xacml.util.XACMLProperties; +import com.google.common.base.Splitter; + + + +public class XacmlAdminUI extends HttpServlet implements PAPNotificationBroadcaster.PAPNotificationBroadcastListener{ + + private static final long serialVersionUID = 1L; + // + // The PAP Engine + // + private PAPPolicyEngine papEngine; + private static Path repositoryPath; + private static Repository repository; + + @Autowired + UserInfoDao userInfoDao; + + @Autowired + SessionFactory sessionfactory; + + @WebServlet(value = "/policy#/*", description = "XACML Admin Console", asyncSupported = true, loadOnStartup = 1, initParams = { @WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.admin.properties", description = "The location of the properties file holding configuration information.") }) + public static class Servlet extends HttpServlet { + private static final long serialVersionUID = -5274600248961852835L; + + @Override + public void init(ServletConfig servletConfig) throws ServletException { + super.init(servletConfig); + // + // Common initialization + // + XACMLRest.xacmlInit(servletConfig); + // + // Initialize GIT repository. + // + XacmlAdminUI.initializeGitRepository(); + // + // Read the Props + // The webapps Action and Config are read when getActionHome or getConfigHome are called + try { + getConfigHome(); + } catch (Exception e) { + throw new ServletException(e); + } + + } + + + @Override + public void destroy() { + if (XacmlAdminUI.repository != null) { + XacmlAdminUI.repository.close(); + } + super.destroy(); + } + } + + private static void initializeGitRepository() throws ServletException { + + try { + XacmlAdminUI.repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY)); + } catch (Exception e) { + XACMLProperties.reloadProperties(); + XacmlAdminUI.repositoryPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_REPOSITORY)); + } + FileRepositoryBuilder builder = new FileRepositoryBuilder(); + try { + XacmlAdminUI.repository = builder.setGitDir(XacmlAdminUI.repositoryPath.toFile()).readEnvironment().findGitDir().setBare().build(); + if (Files.notExists(XacmlAdminUI.repositoryPath)|| Files.notExists(Paths.get(XacmlAdminUI.repositoryPath.toString(), "HEAD"))) { + // + // Create it if it doesn't exist. As a bare repository + XacmlAdminUI.repository.create(); + // + // Add the magic file so remote works. + // + Path daemon = Paths.get(XacmlAdminUI.repositoryPath.toString(), "git-daemon-export-ok"); + Files.createFile(daemon); + } + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + // + // Make sure the workspace directory is created + // + Path workspace = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_WORKSPACE)); + workspace = workspace.toAbsolutePath(); + if (Files.notExists(workspace)) { + try { + Files.createDirectory(workspace); + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + // + // Create the user workspace directory + // + workspace = Paths.get(workspace.toString(), "admin"); + + if (Files.notExists(workspace)) { + try { + Files.createDirectory(workspace); + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + // + // Get the path to where the repository is going to be + // + Path gitPath = Paths.get(workspace.toString(), XacmlAdminUI.repositoryPath.getFileName().toString()); + if (Files.notExists(gitPath)) { + try { + Files.createDirectory(gitPath); + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + // + // Initialize the domain structure + // + String base = null; + String domain = XacmlAdminUI.getDomain(); + if (domain != null) { + for (String part : Splitter.on(':').trimResults().split(domain)) { + if (base == null) { + base = part; + } + Path subdir = Paths.get(gitPath.toString(), part); + if (Files.notExists(subdir)) { + try { + Files.createDirectory(subdir); + Files.createFile(Paths.get(subdir.toString(), ".svnignore")); + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + } + } else { + try { + Files.createFile(Paths.get(workspace.toString(), ".svnignore")); + base = ".svnignore"; + } catch (IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + try { + // + // These are the sequence of commands that must be done initially to + // finish setting up the remote bare repository. + // + Git git = Git.init().setDirectory(gitPath.toFile()).setBare(false).call(); + git.add().addFilepattern(base).call(); + git.commit().setMessage("Initialize Bare Repository").call(); + StoredConfig config = git.getRepository().getConfig(); + config.setString("remote", "origin", "url", XacmlAdminUI.repositoryPath.toAbsolutePath().toString()); + config.setString("remote", "origin", "fetch", "+refs/heads/*:refs/remotes/origin/*"); + config.save(); + git.push().setRemote("origin").add("master").call(); + /* + * This will not work unless + * git.push().setRemote("origin").add("master").call(); is called + * first. Otherwise it throws an exception. However, if the push() + * is called then calling this function seems to add nothing. + * + * git.branchCreate().setName("master") + * .setUpstreamMode(SetupUpstreamMode.SET_UPSTREAM) + * .setStartPoint("origin/master").setForce(true).call(); + */ + } catch (GitAPIException | IOException e) { + throw new ServletException(e.getMessage(), e.getCause()); + } + } + + public UserInfo getUserNameFromUserInfoTable(String createdBy){ + String loginId = createdBy; + Object user = null; + Session session = sessionfactory.openSession(); + user = session.load(UserInfo.class, loginId); + return (UserInfo) user; + } + + @Override + public void updateAllGroups() { + + } + + public PAPPolicyEngine getPapEngine() { + return papEngine; + } + + public void setPapEngine(PAPPolicyEngine papEngine) { + this.papEngine = papEngine; + } + + public static String getConfigHome() { + return Webapps.getConfigHome(); + } + + public static String getDomain() { + return XACMLProperties.getProperty(XACMLRestProperties.PROP_ADMIN_DOMAIN, "urn"); + } + + // get the repository path from property file + public static Path getRepositoryPath() { + if(repositoryPath == null){ + try { + initializeGitRepository(); + } catch (ServletException e) { + + } + } + return repositoryPath; + } + + +} + -- cgit 1.2.3-korg