diff options
163 files changed, 4809 insertions, 4527 deletions
diff --git a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java index 1a6dc4719..8fda22e26 100644 --- a/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java +++ b/BRMSGateway/src/test/java/org/onap/policy/brms/api/BrmsHandlerTest.java @@ -7,9 +7,9 @@ * 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. @@ -29,7 +29,6 @@ import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; -import javax.persistence.Query; import javax.persistence.TypedQuery; import org.junit.Test; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java index bde5e5f09..6e7977419 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiService.java @@ -22,6 +22,7 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.api.pap.PAPException; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; @@ -32,9 +33,11 @@ import java.util.HashSet; import java.util.List; import java.util.Scanner; import java.util.Set; + import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.OnapLoggingContext; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java index 5615b13cf..f2a31db3c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DataToNotifyPdp.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.util.XACMLProperties; import com.google.common.base.Joiner; + import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Paths; @@ -32,6 +33,7 @@ import java.util.Enumeration; import java.util.List; import java.util.Properties; import java.util.TreeSet; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.dao.CommonClassDao; @@ -60,7 +62,6 @@ public class DataToNotifyPdp { // default constructor. } - private static Properties readPipProperties() throws IOException { if (pipProperties == null) { try (FileInputStream inputStream = new FileInputStream(Paths.get("pip.properties").toString())) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java index ce9cad408..2bb2e95bb 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/DictionaryNames.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-Logging * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -18,11 +18,10 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.pap.xacml.rest; /** - * + * * MessageCodes contains all the valid Dictionary names * */ @@ -54,4 +53,3 @@ public enum DictionaryNames { TermList, SearchCriteria } - diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java index 2687799cc..6b9175885 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/Heartbeat.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPStatus; import com.att.research.xacml.util.XACMLProperties; + import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.MalformedURLException; @@ -32,6 +33,7 @@ import java.net.UnknownHostException; import java.util.HashMap; import java.util.HashSet; import java.util.Set; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -42,7 +44,6 @@ import org.onap.policy.xacml.api.pap.OnapPDP; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; - /** * Heartbeat thread - periodically check on PDPs' status. * Heartbeat with all known PDPs. diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java index 9ccccff05..f34d4739f 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/PAPRestConfig.java @@ -24,8 +24,10 @@ package org.onap.policy.pap.xacml.rest; import java.io.FileInputStream; import java.io.InputStream; import java.util.Properties; + import javax.annotation.PostConstruct; import javax.sql.DataSource; + import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.hibernate.SessionFactory; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -45,9 +47,9 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter @Configuration @EnableWebMvc @EnableTransactionManagement -@ComponentScan(basePackages = { "org.onap.*", "com.*" }) +@ComponentScan(basePackages = {"org.onap.*", "com.*"}) public class PAPRestConfig extends WebMvcConfigurerAdapter { - private static final Logger LOGGER = FlexLogger.getLogger(PAPRestConfig.class); + private static final Logger LOGGER = FlexLogger.getLogger(PAPRestConfig.class); private static String dbDriver = null; private static String dbUrl = null; @@ -55,9 +57,9 @@ public class PAPRestConfig extends WebMvcConfigurerAdapter { private static String dbPassword = null; @PostConstruct - public void init(){ + public void init() { Properties prop = new Properties(); - try(InputStream input = new FileInputStream("xacml.pap.properties")) { + try (InputStream input = new FileInputStream("xacml.pap.properties")) { // load a properties file prop.load(input); setDbDriver(prop.getProperty("javax.persistence.jdbc.driver")); @@ -65,8 +67,8 @@ public class PAPRestConfig extends WebMvcConfigurerAdapter { setDbUserName(prop.getProperty("javax.persistence.jdbc.user")); PeCryptoUtils.initAesKey(prop.getProperty(XACMLRestProperties.PROP_AES_KEY)); setDbPassword(PeCryptoUtils.decrypt(prop.getProperty("javax.persistence.jdbc.password"))); - }catch(Exception e){ - LOGGER.error("Exception Occured while loading properties file"+e); + } catch (Exception e) { + LOGGER.error("Exception Occured while loading properties file" + e); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java index 22f919e4b..a7ccfad7f 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdateOthersPAPS.java @@ -22,6 +22,7 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -33,8 +34,10 @@ import java.util.Base64; import java.util.HashMap; import java.util.List; import java.util.Map; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -69,9 +72,10 @@ public class UpdateOthersPAPS { private static CommonClassDao commonClassDao; private static final String contentType = "application/json"; - private static String configType =".Config_"; - private static String actionType =".Action_"; - private static String error ="error"; + private static String configType = ".Config_"; + private static String actionType = ".Action_"; + private static String error = "error"; + public static CommonClassDao getCommonClassDao() { return commonClassDao; } @@ -86,11 +90,11 @@ public class UpdateOthersPAPS { } public UpdateOthersPAPS() { - //Empty Constructor + // Empty Constructor } - @RequestMapping(value="/notifyOtherPAPs", method= RequestMethod.POST) - public void notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response){ + @RequestMapping(value = "/notifyOtherPAPs", method = RequestMethod.POST) + public void notifyOthersPAPsToUpdateConfigurations(HttpServletRequest request, HttpServletResponse response) { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); UpdateObjectData body = new UpdateObjectData(); @@ -100,11 +104,11 @@ public class UpdateOthersPAPS { String currentPap = XACMLRestProperties.getProperty("xacml.rest.pap.url"); List<Object> getPAPUrls = commonClassDao.getData(PolicyDBDaoEntity.class); - if(getPAPUrls != null && !getPAPUrls.isEmpty()){ - for(int i = 0; i < getPAPUrls.size(); i++){ + if (getPAPUrls != null && !getPAPUrls.isEmpty()) { + for (int i = 0; i < getPAPUrls.size(); i++) { PolicyDBDaoEntity papId = (PolicyDBDaoEntity) getPAPUrls.get(i); String papUrl = papId.getPolicyDBDaoUrl(); - if(!papUrl.equals(currentPap)){ + if (!papUrl.equals(currentPap)) { String userName = papId.getUsername(); String password = papId.getPassword(); Base64.Encoder encoder = Base64.getEncoder(); @@ -114,7 +118,7 @@ public class UpdateOthersPAPS { txt = PeCryptoUtils.decrypt(password); } catch (Exception e) { policyLogger.debug(e); - //if we can't decrypt, might as well try it anyway + // if we can't decrypt, might as well try it anyway txt = password; } String encoding = encoder.encodeToString((userName + ":" + txt).getBytes(StandardCharsets.UTF_8)); @@ -126,33 +130,39 @@ public class UpdateOthersPAPS { HttpEntity<?> requestEntity = new HttpEntity<>(body, headers); HttpClientErrorException exception = null; - try{ - restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, requestEntity, String.class); - }catch(Exception e){ - policyLogger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); + try { + restTemplate.exchange(papUrl + "onap/updateConfiguration", HttpMethod.POST, requestEntity, + String.class); + } catch (Exception e) { + policyLogger.error( + XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl, e); exception = new HttpClientErrorException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage()); - if("409 Conflict".equals(e.getMessage())){ + if ("409 Conflict".equals(e.getMessage())) { policyLogger.error(e.getMessage()); response.addHeader(error, e.getMessage()); } } - if(exception != null && exception.getStatusCode()!=null){ + if (exception != null && exception.getStatusCode() != null) { String message; - if(exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)){ - message = XACMLErrorConstants.ERROR_PERMISSIONS +":"+exception.getStatusCode()+":" + "ERROR_AUTH_GET_PERM" ; + if (exception.getStatusCode().equals(HttpStatus.UNAUTHORIZED)) { + message = XACMLErrorConstants.ERROR_PERMISSIONS + ":" + exception.getStatusCode() + ":" + + "ERROR_AUTH_GET_PERM"; policyLogger.error(message); - }else if(exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)){ - message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + } else if (exception.getStatusCode().equals(HttpStatus.BAD_REQUEST)) { + message = XACMLErrorConstants.ERROR_DATA_ISSUE + ":" + exception.getStatusCode() + ":" + + exception.getResponseBodyAsString(); policyLogger.error(message); - }else if(exception.getStatusCode().equals(HttpStatus.NOT_FOUND)){ - message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + exception; + } else if (exception.getStatusCode().equals(HttpStatus.NOT_FOUND)) { + message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while connecting to " + papUrl + + exception; policyLogger.error(message); - }else{ - message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":"+exception.getStatusCode()+":" + exception.getResponseBodyAsString(); + } else { + message = XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + exception.getStatusCode() + ":" + + exception.getResponseBodyAsString(); policyLogger.error(message); } model.put(papUrl, message); - }else{ + } else { model.put(papUrl, "Success"); } } @@ -163,78 +173,80 @@ public class UpdateOthersPAPS { JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); } catch (Exception e) { - policyLogger.error("Exception Occured"+e); + policyLogger.error("Exception Occured" + e); } } } - @RequestMapping(value="/updateConfiguration", method= RequestMethod.POST) + @RequestMapping(value = "/updateConfiguration", method = RequestMethod.POST) @ResponseBody - public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response){ + public void updateConfiguration(@RequestBody UpdateObjectData data, HttpServletResponse response) { String action = data.getAction(); String newPolicyName = data.getNewPolicyName(); String oldPolicyName = data.getOldPolicyName(); - try{ - if("rename".equals(action)){ - if(oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)){ + try { + if ("rename".equals(action)) { + if (oldPolicyName.contains(configType) || oldPolicyName.contains(actionType)) { File file; - if(oldPolicyName.contains(configType)){ + if (oldPolicyName.contains(configType)) { file = new File(Policy.getConfigHome() + File.separator + oldPolicyName); - }else{ + } else { file = new File(Policy.getActionHome() + File.separator + oldPolicyName); } - if(file.exists()){ + if (file.exists()) { File renamefile; - if(oldPolicyName.contains(configType)){ + if (oldPolicyName.contains(configType)) { renamefile = new File(Policy.getConfigHome() + File.separator + newPolicyName); - }else{ + } else { renamefile = new File(Policy.getActionHome() + File.separator + newPolicyName); } - if(file.renameTo(renamefile)){ - policyLogger.info("Policy has been renamed Successfully"+newPolicyName); + if (file.renameTo(renamefile)) { + policyLogger.info("Policy has been renamed Successfully" + newPolicyName); response.addHeader("rename", "Success"); - }else{ + } else { response.addHeader("rename", "Failure"); } } } - }else if("delete".equals(action)){ - if(oldPolicyName.contains(configType)){ + } else if ("delete".equals(action)) { + if (oldPolicyName.contains(configType)) { Files.deleteIfExists(Paths.get(Policy.getConfigHome() + File.separator + oldPolicyName)); - }else if(oldPolicyName.contains("Action_")){ + } else if (oldPolicyName.contains("Action_")) { Files.deleteIfExists(Paths.get(Policy.getActionHome() + File.separator + oldPolicyName)); } - }else if("clonePolicy".equals(action) || "exportPolicy".equals(action)){ - if(newPolicyName.contains(configType)){ - ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao.getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName); + } else if ("clonePolicy".equals(action) || "exportPolicy".equals(action)) { + if (newPolicyName.contains(configType)) { + ConfigurationDataEntity configEntiy = (ConfigurationDataEntity) commonClassDao + .getEntityItem(ConfigurationDataEntity.class, "configurationName", newPolicyName); saveConfigurationData(configEntiy, newPolicyName); - }else if(newPolicyName.contains(actionType)){ - ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao.getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName); + } else if (newPolicyName.contains(actionType)) { + ActionBodyEntity actionEntiy = (ActionBodyEntity) commonClassDao + .getEntityItem(ActionBodyEntity.class, "actionBodyName", newPolicyName); saveActionBodyData(actionEntiy, newPolicyName); } } } catch (IOException e) { - policyLogger.error("Exception Occured While updating Configuration"+e); + policyLogger.error("Exception Occured While updating Configuration" + e); } } - private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName){ - try(FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)){ + private void saveConfigurationData(ConfigurationDataEntity configEntiy, String newPolicyName) { + try (FileWriter fw = new FileWriter(Policy.getConfigHome() + File.separator + newPolicyName)) { BufferedWriter bw = new BufferedWriter(fw); bw.write(configEntiy.getConfigBody()); bw.close(); - }catch (IOException e) { - policyLogger.error("Exception Occured While closing the File input stream"+e); + } catch (IOException e) { + policyLogger.error("Exception Occured While closing the File input stream" + e); } } - private void saveActionBodyData(ActionBodyEntity actionEntiy , String newPolicyName){ - try(FileWriter fw = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)){ + private void saveActionBodyData(ActionBodyEntity actionEntiy, String newPolicyName) { + try (FileWriter fw = new FileWriter(Policy.getActionHome() + File.separator + newPolicyName)) { BufferedWriter bw = new BufferedWriter(fw); bw.write(actionEntiy.getActionBody()); bw.close(); - }catch (IOException e) { - policyLogger.error("Exception Occured While closing the File input stream"+e); + } catch (IOException e) { + policyLogger.error("Exception Occured While closing the File input stream" + e); } } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java index c912a8047..e32ae63b1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/UpdatePdpThread.java @@ -22,12 +22,14 @@ package org.onap.policy.pap.xacml.rest; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPStatus; + import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.List; import java.util.Properties; import java.util.UUID; + import org.onap.policy.common.logging.OnapLoggingContext; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -49,7 +51,6 @@ public class UpdatePdpThread implements Runnable { private OnapLoggingContext loggingContext; private List<Properties> properties; - public UpdatePdpThread(OnapPDP pdp, List<Properties> properties) { this.pdp = pdp; this.properties = properties; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java index 8dc52b861..5805420f1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/XACMLPapServlet.java @@ -20,6 +20,14 @@ package org.onap.policy.pap.xacml.rest; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.api.pap.PDPPolicy; +import com.att.research.xacml.api.pap.PDPStatus; +import com.att.research.xacml.util.FactoryException; +import com.att.research.xacml.util.XACMLProperties; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; + import java.io.File; import java.io.FileInputStream; import java.io.IOException; @@ -35,6 +43,7 @@ import java.util.Properties; import java.util.Set; import java.util.UUID; import java.util.concurrent.CopyOnWriteArrayList; + import javax.persistence.PersistenceException; import javax.servlet.Servlet; import javax.servlet.ServletConfig; @@ -44,6 +53,7 @@ import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.io.IOUtils; import org.onap.policy.common.ia.IntegrityAudit; import org.onap.policy.common.im.AdministrativeStateException; @@ -80,20 +90,17 @@ import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPItemSetChangeNotifier.StdItemSetChangeListener; import org.onap.policy.xacml.std.pap.StdPDPPolicy; import org.onap.policy.xacml.std.pap.StdPDPStatus; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.api.pap.PDPPolicy; -import com.att.research.xacml.api.pap.PDPStatus; -import com.att.research.xacml.util.FactoryException; -import com.att.research.xacml.util.XACMLProperties; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; /** * Servlet implementation class XacmlPapServlet. */ -@WebServlet(description = "Implements the XACML PAP RESTful API.", urlPatterns = {"/"}, +@WebServlet( + description = "Implements the XACML PAP RESTful API.", + urlPatterns = {"/"}, loadOnStartup = 1, - initParams = {@WebInitParam(name = "XACML_PROPERTIES_NAME", value = "xacml.pap.properties", + initParams = {@WebInitParam( + name = "XACML_PROPERTIES_NAME", + value = "xacml.pap.properties", description = "The location of the properties file holding configuration information.")}) public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeListener, Runnable { private static final long serialVersionUID = 1L; @@ -116,8 +123,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * The CopyOnWriteArrayList *should* protect from concurrency errors. This list is seldom * changed but often read, so the costs of this approach make sense. */ - private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = - new CopyOnWriteArrayList<>(); + private static final CopyOnWriteArrayList<String> adminConsoleURLStringList = new CopyOnWriteArrayList<>(); private static String configHome; private static String actionHome; @@ -181,8 +187,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList String hostname = InetAddress.getLocalHost().getCanonicalHostName(); baseLoggingContext.setServer(hostname); } catch (UnknownHostException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "Unable to get hostname for logging", e); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get hostname for logging", e); } // Initialize @@ -207,56 +212,49 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } // Integer will throw an exception of anything is missing or // unrecognized - int papTransWait = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); - int papTransTimeout = Integer.parseInt( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); - int papAuditTimeout = Integer.parseInt( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + int papTransWait = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); + int papTransTimeout = + Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_TIMEOUT)); + int papAuditTimeout = + Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); // Boolean will default to false if anything is missing or // unrecognized - boolean papAuditFlag = Boolean.parseBoolean( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); - boolean papFileSystemAudit = Boolean.parseBoolean( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); - String papDependencyGroups = - XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); + boolean papAuditFlag = + Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG)); + boolean papFileSystemAudit = + Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_FLAG)); + String papDependencyGroups = XACMLProperties.getProperty(XACMLRestProperties.PAP_DEPENDENCY_GROUPS); if (papDependencyGroups == null) { throw new PAPException("papDependencyGroups is null"); } setPAPDependencyGroups(papDependencyGroups); // Integer will throw an exception of anything is missing or // unrecognized - int fpMonitorInterval = Integer.parseInt( - XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); - int failedCounterThreshold = Integer.parseInt(XACMLProperties - .getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); - int testTransInterval = Integer.parseInt( - XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); - int writeFpcInterval = Integer.parseInt( - XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); - LOGGER.debug("\n\n\n**************************************" - + "\n*************************************" + "\n" + "\n papDbDriver = " - + papDbDriver + "\n papDbUrl = " + papDbUrl + "\n papDbUser = " + papDbUser - + "\n papTransWait = " + papTransWait + "\n papTransTimeout = " - + papTransTimeout + "\n papAuditTimeout = " + papAuditTimeout - + "\n papAuditFlag = " + papAuditFlag + "\n papFileSystemAudit = " - + papFileSystemAudit + "\n papResourceName = " + papResourceName - + "\n fpMonitorInterval = " + fpMonitorInterval - + "\n failedCounterThreshold = " + failedCounterThreshold - + "\n testTransInterval = " + testTransInterval + "\n writeFpcInterval = " - + writeFpcInterval + "\n papSiteName = " + papSiteName + "\n papNodeType = " - + papNodeType + "\n papDependencyGroupsList = " + papDependencyGroups - + "\n papIntegrityAuditPeriodSeconds = " + papIntegrityAuditPeriodSeconds - + "\n\n*************************************" + int fpMonitorInterval = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FP_MONITOR_INTERVAL)); + int failedCounterThreshold = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.FAILED_COUNTER_THRESHOLD)); + int testTransInterval = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.TEST_TRANS_INTERVAL)); + int writeFpcInterval = + Integer.parseInt(XACMLProperties.getProperty(IntegrityMonitorProperties.WRITE_FPC_INTERVAL)); + LOGGER.debug("\n\n\n**************************************" + "\n*************************************" + + "\n" + "\n papDbDriver = " + papDbDriver + "\n papDbUrl = " + papDbUrl + "\n papDbUser = " + + papDbUser + "\n papTransWait = " + papTransWait + "\n papTransTimeout = " + papTransTimeout + + "\n papAuditTimeout = " + papAuditTimeout + "\n papAuditFlag = " + papAuditFlag + + "\n papFileSystemAudit = " + papFileSystemAudit + "\n papResourceName = " + papResourceName + + "\n fpMonitorInterval = " + fpMonitorInterval + "\n failedCounterThreshold = " + + failedCounterThreshold + "\n testTransInterval = " + testTransInterval + "\n writeFpcInterval = " + + writeFpcInterval + "\n papSiteName = " + papSiteName + "\n papNodeType = " + papNodeType + + "\n papDependencyGroupsList = " + papDependencyGroups + "\n papIntegrityAuditPeriodSeconds = " + + papIntegrityAuditPeriodSeconds + "\n\n*************************************" + "\n**************************************"); // Pull custom persistence settings Properties properties; try { properties = XACMLProperties.getProperties(); - LOGGER.debug("\n\n\n**************************************" - + "\n**************************************" + "\n\n" + "properties = " - + properties + "\n\n**************************************"); + LOGGER.debug("\n\n\n**************************************" + "\n**************************************" + + "\n\n" + "properties = " + properties + "\n\n**************************************"); } catch (IOException e) { PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "XACMLPapServlet", " Error loading properties with: " + "XACMLProperties.getProperties()"); @@ -278,16 +276,15 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Create the policyDBDao setPolicyDbDao(); // Load our PAP engine, first create a factory - ONAPPapEngineFactory factory = ONAPPapEngineFactory.newInstance( - XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); + ONAPPapEngineFactory factory = ONAPPapEngineFactory + .newInstance(XACMLProperties.getProperty(XACMLProperties.PROP_PAP_PAPENGINEFACTORY)); // The factory knows how to go about creating a PAP Engine setPAPEngine(factory.newEngine()); if (((org.onap.policy.xacml.std.pap.StdEngine) papEngine).wasDefaultGroupJustAdded) { createDefaultGroupOnInit(); } policyDbDao.setPapEngine(XACMLPapServlet.papEngine); - if (Boolean.parseBoolean( - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) { + if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_RUN_AUDIT_FLAG))) { /* * Auditing the local File System groups to be in sync with the Database */ @@ -304,8 +301,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (updatedGroup != null) { papEngine.updateGroup(updatedGroup); } - LOGGER.info( - "PapServlet: updated group is " + papEngine.getDefaultGroup().toString()); + LOGGER.info("PapServlet: updated group is " + papEngine.getDefaultGroup().toString()); // sync up the config data from DB to file system LOGGER.info("PapServlet: Sync config data from DB to file system"); @@ -318,23 +314,20 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Configurable - have the PAP servlet initiate sending the latest // PDP policy/pip configuration // to all its known PDP nodes. - if (Boolean.parseBoolean(XACMLProperties - .getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { + if (Boolean.parseBoolean(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_INITIATE_PDP_CONFIG))) { startInitiateThreadService(new Thread(this)); } // After startup, the PAP does Heartbeat's to each of the PDPs // periodically startHeartBeatService(new Heartbeat(XACMLPapServlet.papEngine)); } catch (FactoryException | PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " Failed to create engine"); - throw new ServletException( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine"); + throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; error: " + e); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Failed to create engine - unexpected error"); - throw new ServletException(XACMLErrorConstants.ERROR_SYSTEM_ERROR - + "PAP not initialized; unexpected error: " + e); + throw new ServletException( + XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PAP not initialized; unexpected error: " + e); } } @@ -344,8 +337,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList try { addNewGroup = policyDbDao.getNewTransaction(); OnapPDPGroup group = papEngine.getDefaultGroup(); - addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), - "automaticallyAdded"); + addNewGroup.createGroup(group.getId(), group.getName(), group.getDescription(), "automaticallyAdded"); addNewGroup.commitTransaction(); addNewGroup = policyDbDao.getNewTransaction(); addNewGroup.changeDefaultGroup(group, "automaticallyAdded"); @@ -364,8 +356,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList initiateThread.start(); } - private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, - Object value) { + private static void mapperWriteValue(ObjectMapper mapper, HttpServletResponse response, Object value) { try { mapper.writeValue(response.getOutputStream(), value); } catch (Exception e) { @@ -412,11 +403,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList papDependencyGroupsFlatArray[i] = papDependencyGroupsFlatArray[i].trim(); } try { - if (XACMLProperties.getProperty( - XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) { - papIntegrityAuditPeriodSeconds = Integer.parseInt(XACMLProperties - .getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) - .trim()); + if (XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS) != null) { + papIntegrityAuditPeriodSeconds = Integer.parseInt( + XACMLProperties.getProperty(XACMLRestProperties.PAP_INTEGRITY_AUDIT_PERIOD_SECONDS).trim()); } } catch (Exception e) { String msg = "integrity_audit_period_seconds "; @@ -426,8 +415,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList throw e; } } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", - " ERROR: Bad property entry"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "XACMLPapServlet", " ERROR: Bad property entry"); throw new PAPException(e); } } @@ -444,8 +432,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList setPapDbDriver(papDbDriver); papDbUrl = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_DB_URL); if (papDbUrl == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", - " ERROR: Bad papDbUrl property entry"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "XACMLPapServlet", " ERROR: Bad papDbUrl property entry"); throw new PAPException("papDbUrl is null"); } setPapDbUrl(papDbUrl); @@ -479,11 +466,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // PDPId File location XACMLPapServlet.pdpFile = XACMLProperties.getProperty(XACMLRestProperties.PROP_PDP_IDFILE); if (XACMLPapServlet.pdpFile == null) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE - + " The PDP Id Authentication File Property is not valid: " + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " The PDP Id Authentication File Property is not valid: " + XACMLRestProperties.PROP_PDP_IDFILE); - throw new PAPException("The PDP Id Authentication File Property :" - + XACMLRestProperties.PROP_PDP_IDFILE + " is not Valid. "); + throw new PAPException("The PDP Id Authentication File Property :" + XACMLRestProperties.PROP_PDP_IDFILE + + " is not Valid. "); } } @@ -517,8 +503,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList XACMLPapServlet.heartbeatThread.join(); } catch (InterruptedException e) { XACMLPapServlet.heartbeatThread.interrupt(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " Error stopping heartbeat"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping heartbeat"); } } if (initiateThread != null) { @@ -527,8 +512,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList initiateThread.join(); } catch (InterruptedException e) { initiateThread.interrupt(); - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " Error stopping thread"); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " Error stopping thread"); } } } @@ -546,8 +530,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - OnapLoggingContext loggingContext = - OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doPost", "PAP.post"); PolicyDBDaoTransaction pdpTransaction = null; try { @@ -557,9 +540,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); } catch (AdministrativeStateException ae) { String message = "POST interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() + "\n Exception Message: " - + PolicyUtils.CATCH_EXCEPTION; + + " but it has an Administrative state of " + im.getStateManager().getAdminState() + + "\n Exception Message: " + PolicyUtils.CATCH_EXCEPTION; LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ae); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); @@ -568,13 +550,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); return; } catch (IntegrityMonitorException ime) { - String message = "POST interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() - + " and a Standby Status of " - + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " - + ime.getMessage(); + String message = + "POST interface called for PAP " + papResourceName + " but it has an Administrative state of " + + im.getStateManager().getAdminState() + " and a Standby Status of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage(); LOGGER.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message, ime); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost im startTransaction"); @@ -611,8 +590,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } loggingContext.metricStarted(); - getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, - papEngine); + getAcServiceInstance().doAcPost(request, response, groupId, loggingContext, papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPost doACPost"); loggingContext.transactionEnded(); @@ -635,23 +613,18 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (CheckPDP.validateID(id)) { pdpTransaction = policyDbDao.getNewTransaction(); try { - pdpTransaction.addPdpToGroup(id, - XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, - "Registered on first startup", Integer.parseInt(jmxport), - "PDP autoregister"); - XACMLPapServlet.papEngine.newPDP(id, - XACMLPapServlet.papEngine.getDefaultGroup(), id, + pdpTransaction.addPdpToGroup(id, XACMLPapServlet.papEngine.getDefaultGroup().getId(), id, + "Registered on first startup", Integer.parseInt(jmxport), "PDP autoregister"); + XACMLPapServlet.papEngine.newPDP(id, XACMLPapServlet.papEngine.getDefaultGroup(), id, "Registered on first startup", Integer.parseInt(jmxport)); - } catch (NullPointerException | PAPException | IllegalArgumentException - | IllegalStateException | PersistenceException | PolicyDBException e) { + } catch (NullPointerException | PAPException | IllegalArgumentException | IllegalStateException + | PersistenceException | PolicyDBException e) { pdpTransaction.rollbackTransaction(); String message = "Failed to create new PDP for id: " + id; - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - " " + message); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); im.endTransaction(); return; } @@ -669,8 +642,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - message); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, message); im.endTransaction(); return; } @@ -709,8 +681,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.error(e); } if (group == null) { - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW - + " PDP not associated with any group, even the default"); + PolicyLogger.error( + MessageCodes.ERROR_PROCESS_FLOW + " PDP not associated with any group, even the default"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); setResponseError(response, HttpServletResponse.SC_UNAUTHORIZED, @@ -783,8 +755,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList LOGGER.debug(XACMLErrorConstants.ERROR_PROCESS_FLOW + "POST exception: " + e, e); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); im.endTransaction(); return; } @@ -810,8 +781,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - OnapLoggingContext loggingContext = - OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doGet", "PAP.get"); loggingContext.metricStarted(); XACMLRest.dumpRequest(request); @@ -835,13 +805,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doGet im startTransaction"); } catch (IntegrityMonitorException ime) { - String message = "GET interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() - + " and a Standby Status of " - + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " - + ime.getMessage(); + String message = + "GET interface called for PAP " + papResourceName + " but it has an Administrative state of " + + im.getStateManager().getAdminState() + " and a Standby Status of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage(); LOGGER.info(message, ime); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -883,8 +850,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // this is from the Admin Console, so handle separately try { loggingContext.metricStarted(); - getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, - papEngine); + getAcServiceInstance().doAcGet(request, response, groupId, loggingContext, papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doGet doACGet"); } catch (IOException e) { @@ -908,8 +874,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // Is it known? if (pdp == null) { // Check if request came from localhost - if ("localhost".equals(request.getRemoteHost()) - || request.getRemoteHost().equals(request.getLocalAddr())) { + if ("localhost".equals(request.getRemoteHost()) || request.getRemoteHost().equals(request.getLocalAddr())) { // Return status information - basically all the groups loggingContext.setServiceName("PAP.getGroups"); Set<OnapPDPGroup> groups = null; @@ -917,12 +882,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList groups = papEngine.getOnapPDPGroups(); } catch (PAPException e) { LOGGER.debug(e); - PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", - " GET exception"); + PolicyLogger.error(MessageCodes.ERROR_UNKNOWN, e, "XACMLPapServlet", " GET exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); im.endTransaction(); return; } @@ -935,8 +898,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList im.endTransaction(); return; } - String message = "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " - + request.getLocalAddr(); + String message = + "Unknown PDP: " + id + " from " + request.getRemoteHost() + " us: " + request.getLocalAddr(); PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + " " + message); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); @@ -983,14 +946,13 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } try { - LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " - + "Policy Name : " + policy.getName() + "\n Policy URI: " - + policy.getLocation().toString()); + LOGGER.warn("PolicyDebugging: Policy Validity: " + policy.isValid() + "\n " + "Policy Name : " + + policy.getName() + "\n Policy URI: " + policy.getLocation().toString()); } catch (PAPException | IOException e) { LOGGER.error(e); } - try (InputStream is = new FileInputStream( - ((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId); + try (InputStream is = + new FileInputStream(((StdPDPGroup) group).getDirectory().toString() + File.separator + policyId); OutputStream os = response.getOutputStream()) { // Send the policy back IOUtils.copy(is, os); @@ -1017,8 +979,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - OnapLoggingContext loggingContext = - OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doPut", "PAP.put"); try { loggingContext.metricStarted(); @@ -1026,13 +987,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPut im startTransaction"); } catch (IntegrityMonitorException e) { - String message = "PUT interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() - + " and a Standby Status of " - + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " - + e.getMessage(); + String message = + "PUT interface called for PAP " + papResourceName + " but it has an Administrative state of " + + im.getStateManager().getAdminState() + " and a Standby Status of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + e.getMessage(); LOGGER.info(message, e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1067,11 +1025,9 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } loggingContext.metricStarted(); LOGGER.info("XACMLPapServlet: Calling PolicyDBDao to handlIncomingHttpNotification"); - HandleIncomingNotifications handleIncomingNotifications = - new HandleIncomingNotifications(); + HandleIncomingNotifications handleIncomingNotifications = new HandleIncomingNotifications(); handleIncomingNotifications.handleIncomingHttpNotification(policyDBDaoRequestUrl, - policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, - policyDBDaoRequestExtraData, this); + policyDBDaoRequestEntityId, policyDBDaoRequestEntityType, policyDBDaoRequestExtraData, this); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doPut handle incoming http notification"); response.setStatus(200); @@ -1159,8 +1115,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // this is from the Admin Console, so handle separately try { loggingContext.metricEnded(); - getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, - papEngine); + getAcServiceInstance().doAcPut(request, response, groupId, loggingContext, papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet goPut doACPut"); } catch (IOException e) { @@ -1217,12 +1172,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } // We do not expect anything from anywhere else. // This method is here in case we ever need to support other operations. - LOGGER.error( - XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag"); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Request does not have groupId or apiflag"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, - "Request does not have groupId or apiflag"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId or apiflag"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See error.log"); im.endTransaction(); @@ -1234,8 +1187,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList @Override protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { - OnapLoggingContext loggingContext = - OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); + OnapLoggingContext loggingContext = OnapLoggingUtils.getLoggingContextForRequest(request, baseLoggingContext); setLoggingContext(loggingContext, "doDelete", "PAP.delete"); try { loggingContext.metricStarted(); @@ -1243,13 +1195,10 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doDelete im startTransaction"); } catch (IntegrityMonitorException ime) { - String message = "DELETE interface called for PAP " + papResourceName - + " but it has an Administrative state of " - + im.getStateManager().getAdminState() - + " and a Standby Status of " - + im.getStateManager().getStandbyStatus() - + "\n Exception Message: " - + ime.getMessage(); + String message = + "DELETE interface called for PAP " + papResourceName + " but it has an Administrative state of " + + im.getStateManager().getAdminState() + " and a Standby Status of " + + im.getStateManager().getStandbyStatus() + "\n Exception Message: " + ime.getMessage(); LOGGER.info(message, ime); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1292,8 +1241,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // this is from the Admin Console, so handle separately try { loggingContext.metricStarted(); - getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, - papEngine); + getAcServiceInstance().doAcDelete(request, response, groupId, loggingContext, papEngine); loggingContext.metricEnded(); PolicyLogger.metrics("XACMLPapServlet doDelete doACDelete"); } catch (IOException e) { @@ -1308,20 +1256,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " Request does not have groupId"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); - setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, - "Request does not have groupId"); + setResponseError(response, HttpServletResponse.SC_BAD_REQUEST, "Request does not have groupId"); im.endTransaction(); } - private boolean isPDPCurrent(Properties policies, Properties pipconfig, - Properties pdpProperties) { + private boolean isPDPCurrent(Properties policies, Properties pipconfig, Properties pdpProperties) { String localRootPolicies = policies.getProperty(XACMLProperties.PROP_ROOTPOLICIES); - String localReferencedPolicies = - policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); + String localReferencedPolicies = policies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES); if (localRootPolicies == null || localReferencedPolicies == null) { - LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE - + "Missing property on PAP server: RootPolicies=" + localRootPolicies - + " ReferencedPolicies=" + localReferencedPolicies); + LOGGER.warn(XACMLErrorConstants.ERROR_DATA_ISSUE + "Missing property on PAP server: RootPolicies=" + + localRootPolicies + " ReferencedPolicies=" + localReferencedPolicies); return false; } // Compare the policies and pipconfig properties to the pdpProperties @@ -1331,8 +1275,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Properties pdpPolicies = XACMLProperties.getPolicyProperties(pdpProperties, false); Properties pdpPipConfig = XACMLProperties.getPipProperties(pdpProperties); if (localRootPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_ROOTPOLICIES)) - && localReferencedPolicies.equals( - pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) + && localReferencedPolicies.equals(pdpPolicies.getProperty(XACMLProperties.PROP_REFERENCEDPOLICIES)) && pdpPipConfig.equals(pipconfig)) { // The PDP is current return true; @@ -1344,8 +1287,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList // property. // Either of these cases means that the PDP is not up-to-date, so // just drop-through to return false. - PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", - " PDP Error"); + PolicyLogger.error(MessageCodes.ERROR_SCHEMA_INVALID, e, "XACMLPapServlet", " PDP Error"); } return false; } @@ -1396,8 +1338,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList * @throws ServletException * @throws IOException */ - public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, - String groupId, OnapLoggingContext loggingContext) throws IOException { + public void updateGroupsFromAPI(HttpServletRequest request, HttpServletResponse response, String groupId, + OnapLoggingContext loggingContext) throws IOException { PolicyDBDaoTransaction acPutTransaction = policyDbDao.getNewTransaction(); PolicyLogger.audit("PolicyDBDaoTransaction started for updateGroupsFromAPI"); try { @@ -1470,8 +1412,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList loggingContext.transactionEnded(); LOGGER.info("Success"); - if (policy != null && ((policy.getId().contains("Config_MS_")) - || (policy.getId().contains("BRMS_Param")))) { + if (policy != null + && ((policy.getId().contains("Config_MS_")) || (policy.getId().contains("BRMS_Param")))) { PushPolicyHandler pushPolicyHandler = PushPolicyHandler.getInstance(); if (pushPolicyHandler.preSafetyCheck(policy, configHome)) { LOGGER.debug("Precheck Successful."); @@ -1482,14 +1424,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return; } catch (PAPException e) { acPutTransaction.rollbackTransaction(); - PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - " API PUT exception"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", " API PUT exception"); loggingContext.transactionEnded(); PolicyLogger.audit("Transaction Failed - See Error.log"); String message = XACMLErrorConstants.ERROR_PROCESS_FLOW + "Exception in request to update group from API - See Error.log on on the PAP."; - setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, - e.getMessage()); + setResponseError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader("error", ADD_GROUP_ERROR); response.addHeader("message", message); @@ -1531,10 +1471,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList try { groups = papEngine.getOnapPDPGroups(); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " getPDPGroups failed"); - throw new IllegalAccessError( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); + throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); } for (OnapPDPGroup group : groups) { groupChanged(group); @@ -1547,10 +1485,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList try { groups = papEngine.getOnapPDPGroups(); } catch (PAPException e) { - PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", - " getPDPGroups failed"); - throw new IllegalAccessError( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); + PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "XACMLPapServlet", " getPDPGroups failed"); + throw new IllegalAccessError(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Unable to get Groups: " + e); } for (OnapPDPGroup group : groups) { groupChanged(group, loggingContext); @@ -1604,8 +1540,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } - private void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext, - List<Properties> pdpDataByGroup) { + private void pdpChanged(OnapPDP pdp, OnapLoggingContext loggingContext, List<Properties> pdpDataByGroup) { Thread t = new Thread(new UpdatePdpThread(pdp, loggingContext, pdpDataByGroup)); if (CheckPDP.validateID(pdp.getId())) { t.start(); @@ -1622,8 +1557,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList return dataToNotify.setPolicyConfigProperties(pdp, papEngine); } - private void testService(OnapLoggingContext loggingContext, HttpServletResponse response) - throws IOException { + private void testService(OnapLoggingContext loggingContext, HttpServletResponse response) throws IOException { LOGGER.info("Test request received"); try { im.evaluateSanity(); @@ -1634,8 +1568,7 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList PolicyLogger.audit("Transaction Failed - See Error.log"); response.setStatus(HttpServletResponse.SC_OK); return; - } catch (ForwardProgressException | AdministrativeStateException - | StandbyStatusException e) { + } catch (ForwardProgressException | AdministrativeStateException | StandbyStatusException e) { String submsg; if (e instanceof ForwardProgressException) { submsg = " is not making forward progress."; @@ -1645,8 +1578,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList submsg = " Standby Status is NOT PROVIDING SERVICE."; } - String message = "GET:/pap/test called and PAP " + papResourceName + submsg - + " Exception Message: " + e.getMessage(); + String message = "GET:/pap/test called and PAP " + papResourceName + submsg + " Exception Message: " + + e.getMessage(); LOGGER.info(message, e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1660,8 +1593,8 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList if (eMsg == null) { eMsg = "No Exception Message"; } - String message = "GET:/pap/test called and PAP " + papResourceName - + " has had a subsystem failure." + " Exception Message: " + eMsg; + String message = "GET:/pap/test called and PAP " + papResourceName + " has had a subsystem failure." + + " Exception Message: " + eMsg; LOGGER.info(message, e); PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + " " + message); loggingContext.transactionEnded(); @@ -1686,18 +1619,16 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList } } - private void setLoggingContext(OnapLoggingContext loggingContext, String methodType, - String serviceName) { + private void setLoggingContext(OnapLoggingContext loggingContext, String methodType, String serviceName) { loggingContext.transactionStarted(); loggingContext.setServiceName(serviceName); if (loggingContext.getRequestId() == null || "".equals(loggingContext.getRequestId())) { UUID requestID = UUID.randomUUID(); loggingContext.setRequestId(requestID.toString()); - PolicyLogger.info("requestID not provided in call to XACMLPapServlet ('" + methodType - + "') so we generated one"); - } else { PolicyLogger.info( - "requestID was provided in call to XACMLPapServlet ('" + methodType + "')"); + "requestID not provided in call to XACMLPapServlet ('" + methodType + "') so we generated one"); + } else { + PolicyLogger.info("requestID was provided in call to XACMLPapServlet ('" + methodType + "')"); } } @@ -1712,14 +1643,12 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList private static void loadWebapps() throws PAPException { if (actionHome == null || configHome == null) { - Path webappsPath = - Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); + Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS)); // Sanity Check if (webappsPath == null) { - PolicyLogger.error("Invalid Webapps Path Location property : " - + XACMLRestProperties.PROP_PAP_WEBAPPS); - throw new PAPException("Invalid Webapps Path Location property : " - + XACMLRestProperties.PROP_PAP_WEBAPPS); + PolicyLogger.error("Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); + throw new PAPException( + "Invalid Webapps Path Location property : " + XACMLRestProperties.PROP_PAP_WEBAPPS); } Path webappsPathConfig = Paths.get(webappsPath.toString() + File.separator + "Config"); Path webappsPathAction = Paths.get(webappsPath.toString() + File.separator + "Action"); @@ -1728,16 +1657,14 @@ public class XACMLPapServlet extends HttpServlet implements StdItemSetChangeList Files.createDirectories(webappsPathConfig); } catch (IOException e) { PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "XACMLPapServlet", - "Failed to create config directory: " - + webappsPathConfig.toAbsolutePath().toString()); + "Failed to create config directory: " + webappsPathConfig.toAbsolutePath().toString()); } } if (Files.notExists(webappsPathAction)) { try { Files.createDirectories(webappsPathAction); } catch (IOException e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Failed to create action directory: " + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Failed to create action directory: " + webappsPathAction.toAbsolutePath().toString(), e); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java index 45c46cb5b..be13c542a 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/SearchData.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.adapters; public class SearchData { @@ -31,70 +32,92 @@ public class SearchData { private String vproAction; private String serviceType; private String bindTextSearch; + public String getQuery() { return query; } + public void setQuery(String query) { this.query = query; } + public String getPolicyType() { return policyType; } + public void setPolicyType(String policyType) { this.policyType = policyType; } + public String getDescriptiveScope() { return descriptiveScope; } + public void setDescriptiveScope(String descriptiveScope) { this.descriptiveScope = descriptiveScope; } + public String getClosedLooppolicyType() { return closedLooppolicyType; } + public void setClosedLooppolicyType(String closedLooppolicyType) { this.closedLooppolicyType = closedLooppolicyType; } + public String getOnapName() { return onapName; } + public void setOnapName(String onapName) { this.onapName = onapName; } + public String getD2Service() { return d2Service; } + public void setD2Service(String d2Service) { this.d2Service = d2Service; } + public String getVnfType() { return vnfType; } + public void setVnfType(String vnfType) { this.vnfType = vnfType; } + public String getPolicyStatus() { return policyStatus; } + public void setPolicyStatus(String policyStatus) { this.policyStatus = policyStatus; } + public String getVproAction() { return vproAction; } + public void setVproAction(String vproAction) { this.vproAction = vproAction; } + public String getServiceType() { return serviceType; } + public void setServiceType(String serviceType) { this.serviceType = serviceType; } + public String getBindTextSearch() { return bindTextSearch; } + public void setBindTextSearch(String bindTextSearch) { this.bindTextSearch = bindTextSearch; } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java index aa59868fe..ead403a02 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectData.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.adapters; public class UpdateObjectData { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java index 780ed86c7..c4076b2ad 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ActionPolicy.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -32,6 +33,7 @@ import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Objects; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; @@ -47,6 +49,7 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObligationExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -82,7 +85,6 @@ public class ActionPolicy extends Policy { List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>(); List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>(); - private CommonClassDao commonClassDao; private static boolean isAttribute = false; @@ -360,7 +362,6 @@ public class ActionPolicy extends Policy { return obligations; } - // if compound setting the inner apply here protected ApplyType getInnerActionApply(String value1Label) { ApplyType actionApply = new ApplyType(); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java index 8ca4dfa01..233add1ad 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,6 +20,9 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; + import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -32,16 +35,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -56,6 +49,13 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + public class ClosedLoopPolicy extends Policy { private static final Logger LOGGER = FlexLogger.getLogger(ClosedLoopPolicy.class); @@ -68,7 +68,7 @@ public class ClosedLoopPolicy extends Policy { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, String jsonBody) { if (policyName.endsWith(".xml")) { @@ -76,7 +76,7 @@ public class ClosedLoopPolicy extends Policy { } try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) { String body = jsonBody; - //Remove the trapMaxAge in Verification Signature + // Remove the trapMaxAge in Verification Signature body = body.replace(",\"trapMaxAge\":null", ""); this.policyAdapter.setJsonBody(body); out.println(body); @@ -85,7 +85,7 @@ public class ClosedLoopPolicy extends Policy { } } - //Utility to read json data from the existing file to a string + // Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); @@ -93,7 +93,7 @@ public class ClosedLoopPolicy extends Policy { } - //create the configuration file based on the policy name on adding the extension as .json + // create the configuration file based on the policy name on adding the extension as .json private String getConfigFile(String filename) { filename = FilenameUtils.removeExtension(filename); if (filename.endsWith(".xml")) { @@ -124,13 +124,13 @@ public class ClosedLoopPolicy extends Policy { return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override public boolean prepareToSave() throws PAPException { if (isPreparedToSave()) { - //we have already done this + // we have already done this return true; } @@ -176,17 +176,13 @@ public class ClosedLoopPolicy extends Policy { // Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); @@ -340,7 +336,7 @@ public class ClosedLoopPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment5); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("RiskType"); assignment6.setCategory(CATEGORY_RESOURCE); @@ -389,7 +385,6 @@ public class ClosedLoopPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment9); - advices.getAdviceExpression().add(advice); return advices; } @@ -399,5 +394,4 @@ public class ClosedLoopPolicy extends Policy { return policyAdapter.getPolicyData(); } - } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java index d6b09086a..1cab7166a 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/ConfigPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * Modified Copyright (C) 2019 Bell Canada. * ================================================================================ @@ -22,6 +22,9 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -33,17 +36,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.utils.PolicyUtils; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -58,6 +50,14 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.utils.PolicyUtils; + public class ConfigPolicy extends Policy { /** @@ -93,7 +93,6 @@ public class ConfigPolicy extends Policy { } } - // Here we are adding the extension for the configurations file based on the // config type selection for saving. private String getConfigFile(String filename) { @@ -103,8 +102,7 @@ public class ConfigPolicy extends Policy { if (id == null) { return filename; } - switch (id.toUpperCase()) - { + switch (id.toUpperCase()) { case JSON_CONFIG: return filename + ".json"; case XML_CONFIG: @@ -127,7 +125,6 @@ public class ConfigPolicy extends Policy { return filename; } - // Validations for Config form /* * FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object... @@ -181,7 +178,7 @@ public class ConfigPolicy extends Policy { } if (!isPreparedToSave()) { - //Prep and configure the policy for saving + // Prep and configure the policy for saving prepareToSave(); } @@ -192,8 +189,8 @@ public class ConfigPolicy extends Policy { return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override public boolean prepareToSave() throws PAPException { @@ -441,7 +438,7 @@ public class ConfigPolicy extends Policy { } } - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskType"); assignment8.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java index 9809ad498..8321505de 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBRMSRuleTemplate.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import java.util.HashMap; @@ -34,25 +35,27 @@ import org.springframework.stereotype.Service; @Service public class CreateBRMSRuleTemplate { - private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class); + private static final Logger LOGGER = FlexLogger.getLogger(CreateBRMSRuleTemplate.class); private static CommonClassDao commonClassDao; @Autowired - public CreateBRMSRuleTemplate(CommonClassDao commonClassDao){ + public CreateBRMSRuleTemplate(CommonClassDao commonClassDao) { CreateBRMSRuleTemplate.commonClassDao = commonClassDao; } - public CreateBRMSRuleTemplate() {} + public CreateBRMSRuleTemplate() { + } public Map<String, String> addRule(String rule, String ruleName, String description, String userID) { - Map<String,String> responseMap = new HashMap<>(); - if(rule!=null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")){ - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BRMSParamTemplate.class); - if(duplicateData!=null && !duplicateData.isEmpty()){ + Map<String, String> responseMap = new HashMap<>(); + if (rule != null && !PolicyUtils.brmsRawValidate(rule).contains("[ERR")) { + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(ruleName, "ruleName", BRMSParamTemplate.class); + if (duplicateData != null && !duplicateData.isEmpty()) { LOGGER.error("Import new service failed. Service already exists"); responseMap.put("DBError", "EXISTS"); return responseMap; - }else{ + } else { BRMSParamTemplate brmsParamTemplate = new BRMSParamTemplate(); brmsParamTemplate.setDescription(description); brmsParamTemplate.setRuleName(ruleName); @@ -63,7 +66,7 @@ public class CreateBRMSRuleTemplate { LOGGER.info("Template created with " + ruleName + " by " + userID); } responseMap.put("success", "success"); - }else{ + } else { LOGGER.debug("Error during validating the rule for creating record for BRMS Param Template"); responseMap.put("error", "VALIDATION"); } @@ -73,8 +76,8 @@ public class CreateBRMSRuleTemplate { public static boolean validateRuleParams(String rule) { CreateBrmsParamPolicy policy = new CreateBrmsParamPolicy(); Map<String, String> paramValues = policy.findType(rule); - for(String key : paramValues.keySet()) { - if(!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))){ + for (String key : paramValues.keySet()) { + if (!PolicyUtils.SUCCESS.equals(PolicyUtils.policySpecialCharValidator(key))) { return false; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java index 6a0c92650..7be1d39b0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsParamPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -20,6 +20,9 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; + import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -41,19 +44,6 @@ import java.util.regex.Pattern; import javax.script.SimpleBindings; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.BRMSParamTemplate; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -68,6 +58,16 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.BRMSParamTemplate; + public class CreateBrmsParamPolicy extends Policy { private static final Logger LOGGER = FlexLogger.getLogger(CreateBrmsParamPolicy.class); @@ -91,19 +91,18 @@ public class CreateBrmsParamPolicy extends Policy { copyMap.put("policyVersion", policyAdapter.getHighestVersion().toString()); copyMap.put("unique", ("p" + policyName + UUID.randomUUID().toString()).replaceAll("[^A-Za-z0-9]", "")); - //Finding all the keys in the Map data-structure. + // Finding all the keys in the Map data-structure. Iterator<String> iterator = copyMap.keySet().iterator(); Pattern p; Matcher m; while (iterator.hasNext()) { - //Converting the first character of the key into a lower case. + // Converting the first character of the key into a lower case. String input = iterator.next(); - String output = Character.toLowerCase(input.charAt(0)) + - (input.length() > 1 ? input.substring(1) : ""); - //Searching for a pattern in the String using the key. + String output = Character.toLowerCase(input.charAt(0)) + (input.length() > 1 ? input.substring(1) : ""); + // Searching for a pattern in the String using the key. p = Pattern.compile("\\$\\{" + output + "\\}"); m = p.matcher(ruleContents); - //Replacing the value with the inputs provided by the user in the editor. + // Replacing the value with the inputs provided by the user in the editor. String finalInput = copyMap.get(input); if (finalInput.contains("$")) { finalInput = finalInput.replace("$", "\\$"); @@ -113,7 +112,6 @@ public class CreateBrmsParamPolicy extends Policy { return ruleContents; } - // Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); @@ -137,7 +135,6 @@ public class CreateBrmsParamPolicy extends Policy { } } - // Here we are adding the extension for the configurations file based on the // config type selection for saving. private String getConfigFile(String filename) { @@ -222,8 +219,7 @@ public class CreateBrmsParamPolicy extends Policy { if (line.contains("*/")) { try { comment = false; - line = line.split("\\/\\*")[0] - + line.split("\\*\\/")[1].replace("*/", ""); + line = line.split("\\/\\*")[0] + line.split("\\*\\/")[1].replace("*/", ""); } catch (Exception e) { LOGGER.debug(e); line = line.split("\\/\\*")[0]; @@ -255,8 +251,8 @@ public class CreateBrmsParamPolicy extends Policy { break; } } - String param = params.toString().replace("declare Params", "").replace("end", "") - .replaceAll("\\s+", ""); + String param = + params.toString().replace("declare Params", "").replace("end", "").replaceAll("\\s+", ""); String[] components = param.split(":"); String caption = ""; for (int i = 0; i < components.length; i++) { @@ -274,7 +270,7 @@ public class CreateBrmsParamPolicy extends Policy { LOGGER.debug(e); nextComponent = components[i]; } - //If the type is of type String then we add the UI Item and type to the map. + // If the type is of type String then we add the UI Item and type to the map. if (nextComponent.startsWith("String")) { type = "String"; mapFieldType.put(caption, type); @@ -330,10 +326,8 @@ public class CreateBrmsParamPolicy extends Policy { StringBuilder body = new StringBuilder(); try { - body.append( - "/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI " + - "purpose. \n\t " + - "<$%BRMSParamTemplate=" + templateValue + "%$> \n"); + body.append("/* Autogenerated Code Please Don't change/remove this comment section. This is for the UI " + + "purpose. \n\t " + "<$%BRMSParamTemplate=" + templateValue + "%$> \n"); body.append("<%$Values="); for (Map.Entry<String, String> entry : ruleAndUIValue.entrySet()) { String uiKey = entry.getKey(); @@ -344,8 +338,8 @@ public class CreateBrmsParamPolicy extends Policy { body.append("$%> \n*/ \n"); body.append(valueFromDictionary + "\n"); } catch (Exception e) { - PolicyLogger - .error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", "Exception saving policy"); + PolicyLogger.error(MessageCodes.ERROR_PROCESS_FLOW, e, "CreateBrmsParamPolicy", + "Exception saving policy"); } saveConfigurations(policyName, body.toString()); @@ -366,12 +360,10 @@ public class CreateBrmsParamPolicy extends Policy { String fileName = policyAdapter.getNewFileName(); String name = fileName.substring(fileName.lastIndexOf("\\") + 1); if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1 - ); + name = fileName.substring(fileName.lastIndexOf("/") + 1); } allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); // Match for ONAPName @@ -419,8 +411,7 @@ public class CreateBrmsParamPolicy extends Policy { } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl( - accessURI).stringValue()); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); accessMatch.setAttributeDesignator(accessAttributeDesignator); accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); @@ -459,24 +450,20 @@ public class CreateBrmsParamPolicy extends Policy { rule.setTarget(targetInRule); rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - configPolicy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() - .add(rule); + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); policyAdapter.setPolicyData(configPolicy); } else { - PolicyLogger.error("Unsupported data object." - + policyAdapter.getData().getClass().getCanonicalName()); + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); } setPreparedToSave(true); return true; } // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, - String fileName) { + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - //Policy Config ID Assignment + // Policy Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("BRMSPARAMID"); @@ -489,8 +476,7 @@ public class CreateBrmsParamPolicy extends Policy { AttributeValueType configNameAttributeValue = new AttributeValueType(); configNameAttributeValue.setDataType(STRING_DATATYPE); configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue)); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); advice.getAttributeAssignmentExpression().add(assignment1); // For Config file Url if configurations are provided. @@ -505,8 +491,7 @@ public class CreateBrmsParamPolicy extends Policy { String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); attributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue)); + assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); // Policy Name Assignment @@ -518,15 +503,12 @@ public class CreateBrmsParamPolicy extends Policy { attributeValue3.setDataType(STRING_DATATYPE); fileName = FilenameUtils.removeExtension(fileName); fileName = fileName + ".xml"; - String name = fileName.substring(fileName.lastIndexOf("\\") + 1 - ); + String name = fileName.substring(fileName.lastIndexOf("\\") + 1); if ((name == null) || (name.equals(""))) { - name = fileName.substring(fileName.lastIndexOf("/") + 1 - ); + name = fileName.substring(fileName.lastIndexOf("/") + 1); } attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue3)); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); // Version Number Assignment @@ -537,8 +519,7 @@ public class CreateBrmsParamPolicy extends Policy { AttributeValueType configNameAttributeValue4 = new AttributeValueType(); configNameAttributeValue4.setDataType(STRING_DATATYPE); configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue4)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); // Onap Name Assignment @@ -549,12 +530,10 @@ public class CreateBrmsParamPolicy extends Policy { AttributeValueType configNameAttributeValue5 = new AttributeValueType(); configNameAttributeValue5.setDataType(STRING_DATATYPE); configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); - assignment5.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue5)); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - - //Config Name Assignment + // Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -564,16 +543,15 @@ public class CreateBrmsParamPolicy extends Policy { configNameAttributeValue6.getContent().add(policyAdapter.getConfigName()); assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); advice.getAttributeAssignmentExpression().add(assignment6); - // Adding Controller Information. + // Adding Controller Information. if (policyAdapter.getBrmsController() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("controller:" + policyAdapter.getBrmsController(), - brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()) - .getController())); + advice.getAttributeAssignmentExpression().add(createResponseAttributes( + "controller:" + policyAdapter.getBrmsController(), + brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); } - // Adding Dependencies. + // Adding Dependencies. if (policyAdapter.getBrmsDependency() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); ArrayList<String> dependencies = new ArrayList<>(); @@ -582,18 +560,18 @@ public class CreateBrmsParamPolicy extends Policy { dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); key.append(dependencyName + ","); } - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); + advice.getAttributeAssignmentExpression() + .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); } - // Dynamic Field Config Attributes. + // Dynamic Field Config Attributes. Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); for (Entry<String, String> map : dynamicFieldConfigAttributes.entrySet()) { advice.getAttributeAssignmentExpression() .add(createResponseAttributes("key:" + map.getKey(), map.getValue())); } - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskType"); assignment8.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java index efa28b2bb..bb46fd6a9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateBrmsRawPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,6 +20,8 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; import java.io.File; import java.io.IOException; @@ -34,15 +36,6 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; -import org.onap.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -57,6 +50,11 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; +import org.onap.policy.rest.adapter.PolicyRestAdapter; public class CreateBrmsRawPolicy extends Policy { @@ -76,8 +74,7 @@ public class CreateBrmsRawPolicy extends Policy { protected void saveConfigurations(String policyName, String jsonBody) { if (policyName.endsWith(".xml")) { - policyName = policyName.substring(0, - policyName.lastIndexOf(".xml")); + policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); } try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".txt")) { out.println(jsonBody); @@ -195,7 +192,6 @@ public class CreateBrmsRawPolicy extends Policy { } allOfOne.getMatch().add(createMatch("PolicyName", name)); - AllOfType allOf = new AllOfType(); // Match for ONAPName @@ -243,8 +239,7 @@ public class CreateBrmsRawPolicy extends Policy { } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); - accessAttributeDesignator.setAttributeId(new IdentifierImpl( - accessURI).stringValue()); + accessAttributeDesignator.setAttributeId(new IdentifierImpl(accessURI).stringValue()); accessMatch.setAttributeDesignator(accessAttributeDesignator); accessMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); @@ -267,8 +262,7 @@ public class CreateBrmsRawPolicy extends Policy { configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); - configAttributeDesignator.setAttributeId(new IdentifierImpl( - configURI).stringValue()); + configAttributeDesignator.setAttributeId(new IdentifierImpl(configURI).stringValue()); configMatch.setAttributeDesignator(configAttributeDesignator); configMatch.setMatchId(FUNCTION_STRING_EQUAL_IGNORE); @@ -284,22 +278,18 @@ public class CreateBrmsRawPolicy extends Policy { rule.setTarget(targetInRule); rule.setAdviceExpressions(getAdviceExpressions(version, policyName)); - configPolicy - .getCombinerParametersOrRuleCombinerParametersOrVariableDefinition() - .add(rule); + configPolicy.getCombinerParametersOrRuleCombinerParametersOrVariableDefinition().add(rule); policyAdapter.setPolicyData(configPolicy); } else { - PolicyLogger.error("Unsupported data object." - + policyAdapter.getData().getClass().getCanonicalName()); + PolicyLogger.error("Unsupported data object." + policyAdapter.getData().getClass().getCanonicalName()); } setPreparedToSave(true); return true; } // Data required for Advice part is setting here. - private AdviceExpressionsType getAdviceExpressions(int version, - String fileName) { + private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { // Policy Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); @@ -314,8 +304,7 @@ public class CreateBrmsRawPolicy extends Policy { AttributeValueType configNameAttributeValue = new AttributeValueType(); configNameAttributeValue.setDataType(STRING_DATATYPE); configNameAttributeValue.getContent().add("Configuration"); - assignment1.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue)); + assignment1.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue)); advice.getAttributeAssignmentExpression().add(assignment1); // For Config file Url if configurations are provided. @@ -330,8 +319,7 @@ public class CreateBrmsRawPolicy extends Policy { String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); AttributeValue.getContent().add(content); - assignment2.setExpression(new ObjectFactory() - .createAttributeValue(AttributeValue)); + assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); // Policy Name Assignment @@ -350,8 +338,7 @@ public class CreateBrmsRawPolicy extends Policy { } System.out.println(name); attributeValue3.getContent().add(name); - assignment3.setExpression(new ObjectFactory() - .createAttributeValue(attributeValue3)); + assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); // Version Number Assignment @@ -362,8 +349,7 @@ public class CreateBrmsRawPolicy extends Policy { AttributeValueType configNameAttributeValue4 = new AttributeValueType(); configNameAttributeValue4.setDataType(STRING_DATATYPE); configNameAttributeValue4.getContent().add(Integer.toString(version)); - assignment4.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue4)); + assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); // Onap Name Assignment @@ -374,12 +360,10 @@ public class CreateBrmsRawPolicy extends Policy { AttributeValueType configNameAttributeValue5 = new AttributeValueType(); configNameAttributeValue5.setDataType(STRING_DATATYPE); configNameAttributeValue5.getContent().add(policyAdapter.getOnapName()); - assignment5.setExpression(new ObjectFactory() - .createAttributeValue(configNameAttributeValue5)); + assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - - //Config Name Assignment + // Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -390,16 +374,15 @@ public class CreateBrmsRawPolicy extends Policy { assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); advice.getAttributeAssignmentExpression().add(assignment6); - // Adding Controller Information. + // Adding Controller Information. if (policyAdapter.getBrmsController() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("controller:" + policyAdapter.getBrmsController(), - brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()) - .getController())); + advice.getAttributeAssignmentExpression().add(createResponseAttributes( + "controller:" + policyAdapter.getBrmsController(), + brmsDicitonaryController.getControllerDataByID(policyAdapter.getBrmsController()).getController())); } - // Adding Dependencies. + // Adding Dependencies. if (policyAdapter.getBrmsDependency() != null) { BRMSDictionaryController brmsDicitonaryController = new BRMSDictionaryController(); ArrayList<String> dependencies = new ArrayList<>(); @@ -408,11 +391,11 @@ public class CreateBrmsRawPolicy extends Policy { dependencies.add(brmsDicitonaryController.getDependencyDataByID(dependencyName).getDependency()); key.append(dependencyName).append(","); } - advice.getAttributeAssignmentExpression().add( - createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); + advice.getAttributeAssignmentExpression() + .add(createResponseAttributes("dependencies:" + key.toString(), dependencies.toString())); } - // Dynamic Field Config Attributes. + // Dynamic Field Config Attributes. Map<String, String> dynamicFieldConfigAttributes = policyAdapter.getDynamicFieldConfigAttributes(); for (Map.Entry<String, String> entry : dynamicFieldConfigAttributes.entrySet()) { String keyField = entry.getKey(); @@ -420,7 +403,7 @@ public class CreateBrmsRawPolicy extends Policy { .add(createResponseAttributes("key:" + keyField, entry.getValue())); } - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("RiskType"); assignment8.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java index e74cc3359..a980e70d8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateClosedLoopPerformanceMetrics.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,6 +20,8 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; import java.io.File; import java.io.PrintWriter; @@ -30,16 +32,6 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; -import org.apache.commons.io.FilenameUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.rest.adapter.PolicyRestAdapter; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -54,40 +46,47 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import org.apache.commons.io.FilenameUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + public class CreateClosedLoopPerformanceMetrics extends Policy { - private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class); + private static final Logger LOGGER = FlexLogger.getLogger(CreateClosedLoopPerformanceMetrics.class); public CreateClosedLoopPerformanceMetrics() { super(); } - public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter){ + public CreateClosedLoopPerformanceMetrics(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, final String jsonBody) { - if(policyName.endsWith(".xml")){ - policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); - } - try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "."+ policyName +".json")){ + if (policyName.endsWith(".xml")) { + policyName = policyName.substring(0, policyName.lastIndexOf(".xml")); + } + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + "." + policyName + ".json")) { out.println(jsonBody); policyAdapter.setJsonBody(jsonBody); policyAdapter.setConfigBodyData(jsonBody); } catch (Exception e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occured" + e); } } - //getting the policy name and setting to configuration on adding .json + // getting the policy name and setting to configuration on adding .json private String getConfigFile(String filename) { filename = FilenameUtils.removeExtension(filename); if (filename.endsWith(".xml")) { filename = filename.substring(0, filename.length() - 4); } - filename = filename +".json"; + filename = filename + ".json"; return filename; } @@ -95,13 +94,13 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ - //Prep and configure the policy for saving + if (!isPreparedToSave()) { + // Prep and configure the policy for saving prepareToSave(); } @@ -109,18 +108,18 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -148,7 +147,6 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { policyName = policyName + ".xml"; } - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); configPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -167,17 +165,13 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { // Adding the matches to AllOfType element Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); // Match for ServiceType allOf.getMatch().add(createMatch("ServiceType", policyAdapter.getServiceType())); @@ -210,7 +204,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -229,7 +224,8 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "CreateClosedLoopPerformanceMetrics", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); @@ -286,7 +282,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { AttributeValueType AttributeValue = new AttributeValueType(); AttributeValue.setDataType(URI_DATATYPE); - String content = CONFIG_URL +"/Config/"+ getConfigFile(policyName); + String content = CONFIG_URL + "/Config/" + getConfigFile(policyName); AttributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); @@ -344,7 +340,7 @@ public class CreateClosedLoopPerformanceMetrics extends Policy { advice.getAttributeAssignmentExpression().add(assignment6); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); assignment7.setAttributeId("RiskType"); assignment7.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java index 103928cbc..9b8854ff8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewMicroServiceModel.java @@ -22,6 +22,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.google.gson.Gson; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -36,6 +37,7 @@ import java.util.List; import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.eelf.MessageCodes; @@ -55,7 +57,6 @@ public class CreateNewMicroServiceModel { private MicroServiceModels newModel = null; private HashMap<String, MSAttributeObject> classMap = new HashMap<>(); - private MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); public CreateNewMicroServiceModel(String fileName, String serviceName, String string, String version) { @@ -145,7 +146,6 @@ public class CreateNewMicroServiceModel { try { - utils.parseTosca(fileName); MSAttributeObject msAttributes = new MSAttributeObject(); @@ -269,7 +269,6 @@ public class CreateNewMicroServiceModel { } mainClass = classMap.get(this.newModel.getModelName()); - if (".yml".equalsIgnoreCase(type)) { newModel.setDependency("[]"); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java index 87c9f9108..0f52b9bae 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/CreateNewOptimizationModel.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -20,6 +20,8 @@ package org.onap.policy.pap.xacml.rest.components; +import com.google.gson.Gson; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; @@ -47,24 +49,22 @@ import org.onap.policy.rest.util.MSAttributeObject; import org.onap.policy.rest.util.MSModelUtils; import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; -import com.google.gson.Gson; - public class CreateNewOptimizationModel { private static final Logger logger = FlexLogger.getLogger(CreateNewOptimizationModel.class); private OptimizationModels newModel = null; - private HashMap<String,MSAttributeObject > classMap = new HashMap<>(); + private HashMap<String, MSAttributeObject> classMap = new HashMap<>(); private static final String EXTRACTDIR = "ExtractDir"; private static final String SUCCESS = "success"; - MSModelUtils utils = new MSModelUtils(XACMLPapServlet.getMsOnapName(), XACMLPapServlet.getMsPolicyName()); public CreateNewOptimizationModel() { super(); } - public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, String randomID) { + public CreateNewOptimizationModel(String importFile, String modelName, String description, String version, + String randomID) { this.newModel = new OptimizationModels(); this.newModel.setVersion(version); @@ -76,14 +76,14 @@ public class CreateNewOptimizationModel { String cleanUpFile = null; Map<String, MSAttributeObject> tempMap = new HashMap<>(); - //Need to delete the file - if (importFile.contains(".zip")){ + // Need to delete the file + if (importFile.contains(".zip")) { extractFolder(randomID + ".zip"); File directory = new File(EXTRACTDIR + File.separator + randomID); List<File> fileList = listModelFiles(directory.toString()); - //get all the files from a director - for (File file : fileList){ - if (file.isFile()){ + // get all the files from a director + for (File file : fileList) { + if (file.isFile()) { processYmlModel(file.toString(), modelName); } } @@ -96,32 +96,32 @@ public class CreateNewOptimizationModel { } catch (IOException e) { logger.error("Failed to unzip model file " + randomID, e); } - }else { - if(importFile.contains(".yml")){ + } else { + if (importFile.contains(".yml")) { - processYmlModel(EXTRACTDIR + File.separator + randomID+".yml", modelName); - cleanUpFile = EXTRACTDIR + File.separator + randomID+".yml"; + processYmlModel(EXTRACTDIR + File.separator + randomID + ".yml", modelName); + cleanUpFile = EXTRACTDIR + File.separator + randomID + ".yml"; - }else{ - tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID+".xmi", MODEL_TYPE.XMI); + } else { + tempMap = utils.processEpackage(EXTRACTDIR + File.separator + randomID + ".xmi", MODEL_TYPE.XMI); classMap.putAll(tempMap); - cleanUpFile = EXTRACTDIR + File.separator + randomID+".xmi"; + cleanUpFile = EXTRACTDIR + File.separator + randomID + ".xmi"; } File deleteFile = new File(cleanUpFile); deleteFile.delete(); } } - private void processYmlModel(String fileName, String modelName){ + private void processYmlModel(String fileName, String modelName) { try { utils.parseTosca(fileName); - MSAttributeObject msAttributes= new MSAttributeObject(); + MSAttributeObject msAttributes = new MSAttributeObject(); msAttributes.setClassName(modelName); - LinkedHashMap<String, String> returnAttributeList =new LinkedHashMap<>(); + LinkedHashMap<String, String> returnAttributeList = new LinkedHashMap<>(); returnAttributeList.put(modelName, utils.getAttributeString()); msAttributes.setAttribute(returnAttributeList); @@ -129,24 +129,24 @@ public class CreateNewOptimizationModel { msAttributes.setMatchingSet(utils.getMatchableValues()); - LinkedHashMap<String, String> returnReferenceList =new LinkedHashMap<>(); + LinkedHashMap<String, String> returnReferenceList = new LinkedHashMap<>(); returnReferenceList.put(modelName, utils.getReferenceAttributes()); msAttributes.setRefAttribute(returnReferenceList); - if(!"".equals(utils.getListConstraints())){ - LinkedHashMap<String, String> enumList =new LinkedHashMap<>(); - String[] listArray=utils.getListConstraints().split("#"); - for(String str:listArray){ - String[] strArr= str.split("="); - if(strArr.length>1){ + if (!"".equals(utils.getListConstraints())) { + LinkedHashMap<String, String> enumList = new LinkedHashMap<>(); + String[] listArray = utils.getListConstraints().split("#"); + for (String str : listArray) { + String[] strArr = str.split("="); + if (strArr.length > 1) { enumList.put(strArr[0], strArr[1]); } } msAttributes.setEnumType(enumList); } - classMap=new LinkedHashMap<>(); + classMap = new LinkedHashMap<>(); classMap.put(modelName, msAttributes); } catch (Exception e) { @@ -174,13 +174,13 @@ public class CreateNewOptimizationModel { int buffer = 2048; File file = new File(zipFile); - try(ZipFile zip = new ZipFile(EXTRACTDIR + File.separator +file);){ - String newPath = zipFile.substring(0, zipFile.length() - 4); + try (ZipFile zip = new ZipFile(EXTRACTDIR + File.separator + file);) { + String newPath = zipFile.substring(0, zipFile.length() - 4); new File(newPath).mkdir(); Enumeration zipFileEntries = zip.entries(); // Process each entry - while (zipFileEntries.hasMoreElements()){ + while (zipFileEntries.hasMoreElements()) { // grab a zip file entry ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); @@ -189,13 +189,13 @@ public class CreateNewOptimizationModel { destinationParent.mkdirs(); - if (!entry.isDirectory()){ + if (!entry.isDirectory()) { int currentByte; byte[] data = new byte[buffer]; - try(FileOutputStream fos = new FileOutputStream(destFile); + try (FileOutputStream fos = new FileOutputStream(destFile); BufferedInputStream is = new BufferedInputStream(zip.getInputStream(entry)); - BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) { + BufferedOutputStream dest = new BufferedOutputStream(fos, buffer)) { while ((currentByte = is.read(data, 0, buffer)) != -1) { dest.write(data, 0, currentByte); @@ -204,7 +204,7 @@ public class CreateNewOptimizationModel { } } - if (currentEntry.endsWith(".zip")){ + if (currentEntry.endsWith(".zip")) { extractFolder(destFile.getAbsolutePath()); } } @@ -218,38 +218,40 @@ public class CreateNewOptimizationModel { Map<String, String> successMap = new HashMap<>(); MSAttributeObject mainClass; - if (!classMap.containsKey(this.newModel.getModelName())){ - logger.error("Model Provided does not contain the service name provided in request. Unable to import new model"); - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", "Unable to pull out required values, file missing service name provided in request"); + if (!classMap.containsKey(this.newModel.getModelName())) { + logger.error( + "Model Provided does not contain the service name provided in request. Unable to import new model"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, "AddValuesToNewModel", + "Unable to pull out required values, file missing service name provided in request"); successMap.put("error", "MISSING"); return successMap; } mainClass = classMap.get(this.newModel.getModelName()); newModel.setDependency("[]"); - if(mainClass.getSubClass() != null){ - String value = new Gson().toJson(mainClass.getSubClass()); - newModel.setSubattributes(value); + if (mainClass.getSubClass() != null) { + String value = new Gson().toJson(mainClass.getSubClass()); + newModel.setSubattributes(value); } - if(mainClass.getAttribute() != null){ - String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndexForAttributes= attributes.indexOf('='); - String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1); + if (mainClass.getAttribute() != null) { + String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes = attributes.indexOf('='); + String atttributesAfterFirstEquals = attributes.substring(equalsIndexForAttributes + 1); this.newModel.setAttributes(atttributesAfterFirstEquals); } - if(mainClass.getRefAttribute() != null){ - String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndex= refAttributes.indexOf('='); - String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1); + if (mainClass.getRefAttribute() != null) { + String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex = refAttributes.indexOf('='); + String refAttributesAfterFirstEquals = refAttributes.substring(equalsIndex + 1); this.newModel.setRefattributes(refAttributesAfterFirstEquals); } - if(mainClass.getEnumType() != null){ + if (mainClass.getEnumType() != null) { this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); } - if(mainClass.getMatchingSet() != null){ + if (mainClass.getMatchingSet() != null) { this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); } @@ -258,14 +260,15 @@ public class CreateNewOptimizationModel { } - public Map<String, String> saveImportService(){ + public Map<String, String> saveImportService() { String modelName = this.newModel.getModelName(); String importedBy = "API"; String version = this.newModel.getVersion(); Map<String, String> successMap = new HashMap<>(); CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+version); - if(result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + version); + if (result.isEmpty()) { OptimizationModels model = new OptimizationModels(); model.setModelName(modelName); model.setVersion(version); @@ -283,7 +286,7 @@ public class CreateNewOptimizationModel { model.setUserCreatedBy(userInfo); dbConnection.save(model); successMap.put(SUCCESS, SUCCESS); - }else{ + } else { successMap.put("DBError", "EXISTS"); logger.error("Import new service failed. Service already exists"); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java index da5c6aea1..ed1d551b4 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicy.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.XACML3; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.std.IdentifierImpl; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -40,6 +41,25 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; + import org.apache.commons.lang3.StringEscapeUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -63,25 +83,6 @@ import org.onap.policy.xacml.std.pip.engines.aaf.AAFEngine; import org.onap.policy.xacml.util.XACMLPolicyScanner; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ApplyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ConditionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableReferenceType; - @Component public class DecisionPolicy extends Policy { @@ -103,7 +104,6 @@ public class DecisionPolicy extends Policy { private static final String POLICY_NAME = "PolicyName"; private static final String DESCRIPTION = "description"; - List<String> dynamicLabelRuleAlgorithms = new LinkedList<>(); List<String> dynamicFieldComboRuleAlgorithms = new LinkedList<>(); List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>(); @@ -154,16 +154,15 @@ public class DecisionPolicy extends Policy { private void readRawPolicyData() { Object policy; if ("API".equalsIgnoreCase(policyAdapter.getApiflag())) { - policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream(StringEscapeUtils - .unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8))); + policy = XACMLPolicyScanner.readPolicy(new ByteArrayInputStream( + StringEscapeUtils.unescapeXml(policyAdapter.getRawXacmlPolicy()).getBytes(StandardCharsets.UTF_8))); } else { policy = XACMLPolicyScanner.readPolicy( new ByteArrayInputStream(policyAdapter.getRawXacmlPolicy().getBytes(StandardCharsets.UTF_8))); } String policyRawDesc; if (policy instanceof PolicySetType) { - policyRawDesc = - ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; + policyRawDesc = ((PolicySetType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; ((PolicySetType) policy).setDescription(policyRawDesc); } else { policyRawDesc = ((PolicyType) policy).getDescription() + "@#RuleProvider@#Decision_Raw@#RuleProvider@#"; @@ -204,13 +203,13 @@ public class DecisionPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - if(policyAdapter.getRuleProvider().equals(GUARD_YAML) || - policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) || - policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)){ + if (policyAdapter.getRuleProvider().equals(GUARD_YAML) || policyAdapter.getRuleProvider().equals(GUARD_BL_YAML) + || policyAdapter.getRuleProvider().equals(GUARD_MIN_MAX)) { Map<String, String> yamlParams = new HashMap<>(); - String blackListEntryType = policyAdapter.getBlackListEntryType() != null - ? policyAdapter.getBlackListEntryType() : "Use Manual Entry"; + String blackListEntryType = + policyAdapter.getBlackListEntryType() != null ? policyAdapter.getBlackListEntryType() + : "Use Manual Entry"; String description = policyAdapter.getPolicyDescription() != null ? policyAdapter.getPolicyDescription() : "YAML Guard Policy"; yamlParams.put(DESCRIPTION, description + "@blEntry@" + blackListEntryType + "@blEntry@"); @@ -428,8 +427,7 @@ public class DecisionPolicy extends Policy { yamlSpecs.put("guardActiveStart", constraints.getActive_time_range().get("start")); yamlSpecs.put("guardActiveEnd", constraints.getActive_time_range().get("end")); String xacmlPolicyContent = SafePolicyBuilder.generateXacmlGuard(xacmlTemplateContent, yamlSpecs, - constraints.getBlacklist(), - guard.getMatch_parameters().getTargets()); + constraints.getBlacklist(), guard.getMatch_parameters().getTargets()); // Convert the Policy into Stream input to Policy Adapter. Object policy = XACMLPolicyScanner @@ -713,7 +711,8 @@ public class DecisionPolicy extends Policy { if (!attributeId.startsWith("S_")) { ApplyType innerDecisionApply = generateApplyTypeDataType(functionKey); AttributeDesignatorType attributeDesignator = generateAttributeDesignatorDataType(functionKey); - AttributeValueType decisionConditionAttributeValue = generateAttributeValueTypeDataType(functionKey); + AttributeValueType decisionConditionAttributeValue = + generateAttributeValueTypeDataType(functionKey); if (attributeId != null) { attributeDesignator.setCategory(CATEGORY_RESOURCE); @@ -793,7 +792,6 @@ public class DecisionPolicy extends Policy { dataTypeList.add(dataType); } - private String getDataType(String key) { DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key); @@ -826,8 +824,7 @@ public class DecisionPolicy extends Policy { private AttributeDesignatorType generateAttributeDesignatorDataType(String functionKey) { AttributeDesignatorType attributeDesignator = new AttributeDesignatorType(); - switch(functionKey.toLowerCase()) - { + switch (functionKey.toLowerCase()) { case "integer": attributeDesignator.setDataType(INTEGER_DATATYPE); break; @@ -839,8 +836,7 @@ public class DecisionPolicy extends Policy { private ApplyType generateApplyTypeDataType(String functionKey) { ApplyType applyType = new ApplyType(); - switch(functionKey.toLowerCase()) - { + switch (functionKey.toLowerCase()) { case "integer": applyType.setFunctionId(FUNTION_INTEGER_ONE_AND_ONLY); break; @@ -852,8 +848,7 @@ public class DecisionPolicy extends Policy { private AttributeValueType generateAttributeValueTypeDataType(String functionKey) { AttributeValueType applyType = new AttributeValueType(); - switch(functionKey.toLowerCase()) - { + switch (functionKey.toLowerCase()) { case "integer": applyType.setDataType(INTEGER_DATATYPE); break; @@ -864,8 +859,10 @@ public class DecisionPolicy extends Policy { } private void applyTwoTextFieldRuleAttribute(ApplyType decisionApply, String value1, String functionKey) { - decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); - decisionApply.getExpression().add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); + decisionApply.getExpression() + .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); + decisionApply.getExpression() + .add(new ObjectFactory().createApply(generateApplyTypeDataType(value1, functionKey))); } private ApplyType generateApplyTypeDataType(String value1, String functionKey) { @@ -874,10 +871,8 @@ public class DecisionPolicy extends Policy { attributeDesignator.setCategory(CATEGORY_RESOURCE); // Here set actual field values - attributeDesignator - .setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8)); - innerApply.getExpression() - .add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); + attributeDesignator.setAttributeId(value1.contains("resource:") ? value1.substring(9) : value1.substring(8)); + innerApply.getExpression().add(new ObjectFactory().createAttributeDesignator(attributeDesignator)); return innerApply; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java index eca473f41..01c211cdb 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicy.java @@ -26,6 +26,7 @@ import com.att.research.xacml.std.IdentifierImpl; import com.fasterxml.jackson.databind.JsonNode; import com.github.fge.jackson.JsonLoader; import com.github.fge.jsonpatch.diff.JsonDiff; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -41,11 +42,27 @@ import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; + import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; import javax.json.JsonReader; import javax.script.SimpleBindings; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.io.FilenameUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -66,19 +83,6 @@ import org.onap.policy.rest.jpa.TermList; import org.onap.policy.rest.jpa.UserInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.EffectType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @Component public class FirewallConfigPolicy extends Policy { @@ -114,11 +118,11 @@ public class FirewallConfigPolicy extends Policy { LOGGER.debug("Configuration is succesfully saved"); } } catch (IOException e) { - LOGGER.error("Save of configuration to file" +fileName+ "failed",e); + LOGGER.error("Save of configuration to file" + fileName + "failed", e); } } - //Utility to read json data from the existing file to a string + // Utility to read json data from the existing file to a string static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); @@ -127,11 +131,11 @@ public class FirewallConfigPolicy extends Policy { @Override public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ + if (!isPreparedToSave()) { prepareToSave(); } @@ -139,9 +143,10 @@ public class FirewallConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); Boolean dbIsUpdated = false; - if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())){ + if (policyAdapter.getApiflag() != null && "admin".equalsIgnoreCase(policyAdapter.getApiflag())) { if (policyAdapter.isEditPolicy()) { - dbIsUpdated = updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody()); + dbIsUpdated = + updateFirewallDictionaryData(policyAdapter.getJsonBody(), policyAdapter.getPrevJsonBody()); } else { try { dbIsUpdated = insertFirewallDicionaryData(policyAdapter.getJsonBody()); @@ -153,14 +158,14 @@ public class FirewallConfigPolicy extends Policy { dbIsUpdated = true; } - if(dbIsUpdated) { - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + if (dbIsUpdated) { + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); } else { PolicyLogger.error("Failed to Update the Database Dictionary Tables."); - //remove the new json file + // remove the new json file String jsonBody = policyAdapter.getPrevJsonBody(); - if (jsonBody!=null){ + if (jsonBody != null) { saveConfigurations(policyName, jsonBody); } else { saveConfigurations(policyName, ""); @@ -171,13 +176,13 @@ public class FirewallConfigPolicy extends Policy { return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -196,13 +201,13 @@ public class FirewallConfigPolicy extends Policy { } policyName = policyAdapter.getNewFileName(); - //String oldPolicyName = policyName.replace(".xml", ""); + // String oldPolicyName = policyName.replace(".xml", ""); String scope = policyName.substring(0, policyName.indexOf('.')); - String dbPolicyName = policyName.substring(policyName.indexOf('.')+1).replace(".xml", ""); + String dbPolicyName = policyName.substring(policyName.indexOf('.') + 1).replace(".xml", ""); - int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.')+1)); - dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.')+1); - if(oldversion > 1){ + int oldversion = Integer.parseInt(dbPolicyName.substring(dbPolicyName.lastIndexOf('.') + 1)); + dbPolicyName = dbPolicyName.substring(0, dbPolicyName.lastIndexOf('.') + 1); + if (oldversion > 1) { oldversion = oldversion - 1; dbPolicyName = dbPolicyName + oldversion + ".xml"; } @@ -277,7 +282,8 @@ public class FirewallConfigPolicy extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -298,7 +304,8 @@ public class FirewallConfigPolicy extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "FirewallConfigPolicy", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); @@ -332,7 +339,7 @@ public class FirewallConfigPolicy extends Policy { // Data required for Advice part is setting here. private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { - //Firewall Config ID Assignment + // Firewall Config ID Assignment AdviceExpressionsType advices = new AdviceExpressionsType(); AdviceExpressionType advice = new AdviceExpressionType(); advice.setAdviceId("firewallConfigID"); @@ -349,7 +356,7 @@ public class FirewallConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment1); // For Config file Url if configurations are provided. - //URL ID Assignment + // URL ID Assignment AttributeAssignmentExpressionType assignment2 = new AttributeAssignmentExpressionType(); assignment2.setAttributeId("URLID"); assignment2.setCategory(CATEGORY_RESOURCE); @@ -365,7 +372,7 @@ public class FirewallConfigPolicy extends Policy { assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); - //Policy Name Assignment + // Policy Name Assignment AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); assignment3.setAttributeId("PolicyName"); assignment3.setCategory(CATEGORY_RESOURCE); @@ -382,7 +389,7 @@ public class FirewallConfigPolicy extends Policy { assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); - //Version Number Assignment + // Version Number Assignment AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); assignment4.setAttributeId("VersionNumber"); assignment4.setCategory(CATEGORY_RESOURCE); @@ -393,7 +400,7 @@ public class FirewallConfigPolicy extends Policy { assignment4.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue4)); advice.getAttributeAssignmentExpression().add(assignment4); - //Onap Name Assignment + // Onap Name Assignment AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); assignment5.setAttributeId("matching:" + ONAPID); assignment5.setCategory(CATEGORY_RESOURCE); @@ -403,7 +410,7 @@ public class FirewallConfigPolicy extends Policy { assignment5.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue5)); advice.getAttributeAssignmentExpression().add(assignment5); - //Config Name Assignment + // Config Name Assignment AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -414,7 +421,7 @@ public class FirewallConfigPolicy extends Policy { assignment6.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue6)); advice.getAttributeAssignmentExpression().add(assignment6); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); assignment7.setAttributeId("RiskType"); assignment7.setCategory(CATEGORY_RESOURCE); @@ -466,19 +473,18 @@ public class FirewallConfigPolicy extends Policy { return advices; } - - private Boolean insertFirewallDicionaryData (String jsonBody) throws SQLException { + private Boolean insertFirewallDicionaryData(String jsonBody) throws SQLException { CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); JsonObject json = null; if (jsonBody != null) { - //Read jsonBody to JsonObject + // Read jsonBody to JsonObject json = stringToJson(jsonBody); JsonArray firewallRules = null; JsonArray serviceGroup = null; JsonArray addressGroup = null; - //insert data into tables + // insert data into tables try { firewallRules = json.getJsonArray("firewallRuleList"); serviceGroup = json.getJsonArray("serviceGroups"); @@ -487,28 +493,28 @@ public class FirewallConfigPolicy extends Policy { * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables */ if (firewallRules != null) { - for(int i = 0;i<firewallRules.size();i++) { + for (int i = 0; i < firewallRules.size(); i++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject ruleListobj = firewallRules.getJsonObject(i); - //get values from JSON fields of firewallRulesList Array + // get values from JSON fields of firewallRulesList Array String ruleName = ruleListobj.get("ruleName").toString(); String action = ruleListobj.get("action").toString(); String description = ruleListobj.get("description").toString(); List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName); - if(result != null && !result.isEmpty()){ + if (result != null && !result.isEmpty()) { TermList termEntry = (TermList) result.get(0); dbConnection.delete(termEntry); } - //getting fromZone Array field from the firewallRulesList + // getting fromZone Array field from the firewallRulesList JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); String fromZoneString = null; - for (int fromZoneIndex = 0;fromZoneIndex<fromZoneArray.size(); fromZoneIndex++) { + for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) { String value = fromZoneArray.get(fromZoneIndex).toString(); value = value.replace("\"", ""); if (fromZoneString != null) { @@ -517,12 +523,12 @@ public class FirewallConfigPolicy extends Policy { fromZoneString = value; } } - String fromZoneInsert = "'"+fromZoneString+"'"; + String fromZoneInsert = "'" + fromZoneString + "'"; - //getting toZone Array field from the firewallRulesList + // getting toZone Array field from the firewallRulesList JsonArray toZoneArray = ruleListobj.getJsonArray("toZones"); String toZoneString = null; - for (int toZoneIndex = 0; toZoneIndex<toZoneArray.size(); toZoneIndex++) { + for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) { String value = toZoneArray.get(toZoneIndex).toString(); value = value.replace("\"", ""); if (toZoneString != null) { @@ -531,19 +537,19 @@ public class FirewallConfigPolicy extends Policy { toZoneString = value; } } - String toZoneInsert = "'"+toZoneString+"'"; + String toZoneInsert = "'" + toZoneString + "'"; - //getting sourceList Array fields from the firewallRulesList + // getting sourceList Array fields from the firewallRulesList JsonArray srcListArray = ruleListobj.getJsonArray("sourceList"); String srcListString = null; - for (int srcListIndex = 0; srcListIndex< srcListArray.size(); srcListIndex++) { + for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) { JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex); String type = srcListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = srcListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = srcListObj.get("value").toString(); @@ -552,19 +558,19 @@ public class FirewallConfigPolicy extends Policy { srcListString = getLeftOrRight(srcListString, value); } - String srcListInsert = "'"+srcListString+"'"; + String srcListInsert = "'" + srcListString + "'"; - //getting destinationList Array fields from the firewallRulesList + // getting destinationList Array fields from the firewallRulesList JsonArray destListArray = ruleListobj.getJsonArray("destinationList"); String destListString = null; - for (int destListIndex = 0; destListIndex <destListArray.size(); destListIndex++) { + for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) { JsonObject destListObj = destListArray.getJsonObject(destListIndex); String type = destListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destListObj.get("value").toString(); @@ -572,19 +578,20 @@ public class FirewallConfigPolicy extends Policy { destListString = getLeftOrRight(destListString, value); } - String destListInsert = "'"+destListString+"'"; + String destListInsert = "'" + destListString + "'"; - //getting destServices Array fields from the firewallRulesList + // getting destServices Array fields from the firewallRulesList JsonArray destServicesArray = ruleListobj.getJsonArray("destServices"); String destPortListString = null; - for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) { + for (int destPortListIndex = 0; destPortListIndex < destServicesArray + .size(); destPortListIndex++) { JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex); String type = destServicesObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destServicesObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destServicesObj.get("value").toString(); @@ -592,7 +599,7 @@ public class FirewallConfigPolicy extends Policy { destPortListString = getLeftOrRight(destPortListString, value); } - String destPortListInsert = "'"+destPortListString+"'"; + String destPortListInsert = "'" + destPortListString + "'"; /* * Create Queries to INSERT data into database tables and execute @@ -624,35 +631,35 @@ public class FirewallConfigPolicy extends Policy { * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables */ if (serviceGroup != null) { - for(int i = 0; i < serviceGroup.size() ; i++) { + for (int i = 0; i < serviceGroup.size(); i++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject svcGroupListobj = serviceGroup.getJsonObject(i); String serviceListName = svcGroupListobj.get("name").toString(); String description = null; - if (svcGroupListobj.containsKey("description")){ + if (svcGroupListobj.containsKey("description")) { description = svcGroupListobj.get("description").toString(); } - //getting members Array from the serviceGroup + // getting members Array from the serviceGroup JsonArray membersArray = svcGroupListobj.getJsonArray("members"); - //String type = svcGroupListobj.get("type").toString(); + // String type = svcGroupListobj.get("type").toString(); Boolean isServiceGroup = false; - if (membersArray!=null){ + if (membersArray != null) { String membersType = membersArray.getJsonObject(0).get("type").toString(); if (membersType.contains("REFERENCE")) { isServiceGroup = true; } } - //Insert values into GROUPSERVICELIST table if name begins with Group + // Insert values into GROUPSERVICELIST table if name begins with Group if (isServiceGroup) { saveGroupServiceListTableToDb(dbConnection, serviceListName, membersArray); - } else { //Insert JSON data serviceList table, protollist table, and portlist table + } else { // Insert JSON data serviceList table, protollist table, and portlist table String type = svcGroupListobj.get("type").toString(); String transportProtocol = svcGroupListobj.get("transportProtocol").toString(); String ports = svcGroupListobj.get("ports").toString(); @@ -660,7 +667,8 @@ public class FirewallConfigPolicy extends Policy { /* * Create Queries to INSERT data into database table and execute */ - saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, ports); + saveServiceListToDb(dbConnection, serviceListName, description, type, transportProtocol, + ports); saveProtocolListToDb(dbConnection, transportProtocol); @@ -673,19 +681,19 @@ public class FirewallConfigPolicy extends Policy { * Inserting addressGroup data into the ADDRESSGROUP table */ if (addressGroup != null) { - for(int i = 0; i < addressGroup.size(); i++) { + for (int i = 0; i < addressGroup.size(); i++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject addressGroupObj = addressGroup.getJsonObject(i); - //create JSON array for members + // create JSON array for members JsonArray membersArray = addressGroupObj.getJsonArray("members"); String addressGroupName = addressGroupObj.get("name").toString(); String description = null; - if (addressGroupObj.containsKey("description")){ + if (addressGroupObj.containsKey("description")) { description = addressGroupObj.get("description").toString(); } @@ -693,13 +701,11 @@ public class FirewallConfigPolicy extends Policy { String type = null; for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); - //String value = membersObj.get("value").toString(); type = membersObj.get("type").toString().replace("\"", ""); - String value = null; prefixIP = getName(prefixIP, membersObj, type); } - String prefixList = "'"+prefixIP+"'"; + String prefixList = "'" + prefixIP + "'"; Boolean isAddressGroup = type.contains("REFERENCE"); @@ -711,8 +717,9 @@ public class FirewallConfigPolicy extends Policy { } } removeDuplicateValuesFromLookup(dbConnection); - }catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception getting Json values"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", + "Exception getting Json values"); return false; } return true; @@ -731,33 +738,34 @@ public class FirewallConfigPolicy extends Policy { + "WHERE protocollist.id > p1.id AND protocollist.protocolname = p1.protocolname;"; dbConnection.updateQuery(protoDelete); - //PortList Table + // PortList Table String portListDelete = "DELETE FROM portlist USING portlist, portlist p1 " + "WHERE portlist.id > p1.id AND portlist.portname = p1.portname; "; dbConnection.updateQuery(portListDelete); - //PrefixList Table + // PrefixList Table String prefixListDelete = "DELETE FROM prefixlist USING prefixlist, prefixlist p1 " + "WHERE prefixlist.id > p1.id AND prefixlist.pl_name = p1.pl_name AND " + "prefixlist.pl_value = p1.pl_value AND prefixlist.description = p1.description; "; dbConnection.updateQuery(prefixListDelete); - //GroupServiceList + // GroupServiceList String groupServiceDelete = "DELETE FROM groupservicelist USING groupservicelist, groupservicelist g1 " + "WHERE groupservicelist.id > g1.id AND groupservicelist.name = g1.name AND " + "groupservicelist.serviceList = g1.serviceList; "; dbConnection.updateQuery(groupServiceDelete); } - private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, JsonArray membersArray) { + private void saveGroupServiceListTableToDb(CommonClassDaoImpl dbConnection, String serviceListName, + JsonArray membersArray) { String name = null; - for (int membersIndex = 0; membersIndex< membersArray.size(); membersIndex++) { + for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); String type = membersObj.get("type").toString().replace("\"", ""); name = getName(name, membersObj, type); } - String nameInsert = "'"+name+"'"; + String nameInsert = "'" + name + "'"; GroupServiceList groupServiceEntry = new GroupServiceList(); groupServiceEntry.setGroupName(serviceListName); groupServiceEntry.setServiceList(nameInsert); @@ -766,9 +774,9 @@ public class FirewallConfigPolicy extends Policy { private String getName(String name, JsonObject membersObj, String type) { String value; - if(type.equals("REFERENCE")||type.equals("GROUP")||type.equals("SERVICE")){ + if (type.equals("REFERENCE") || type.equals("GROUP") || type.equals("SERVICE")) { value = membersObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = membersObj.get("value").toString(); @@ -791,7 +799,6 @@ public class FirewallConfigPolicy extends Policy { return name; } - private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) { CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); JsonObject oldJson = null; @@ -802,7 +809,7 @@ public class FirewallConfigPolicy extends Policy { oldJson = stringToJson(prevJsonBody); newJson = stringToJson(jsonBody); - //if no changes to the json then return true + // if no changes to the json then return true if (oldJson != null && oldJson.equals(newJson)) { return true; } @@ -815,12 +822,12 @@ public class FirewallConfigPolicy extends Policy { serviceGroup = newJson.getJsonArray("serviceGroups"); addressGroup = newJson.getJsonArray("addressGroups"); - //insert data into tables + // insert data into tables try { JsonNode jsonDiff = createPatch(jsonBody, prevJsonBody); - for (int i = 0; i<jsonDiff.size(); i++) { - //String path = jsonDiff.get(i).asText(); + for (int i = 0; i < jsonDiff.size(); i++) { + // String path = jsonDiff.get(i).asText(); String jsonpatch = jsonDiff.get(i).toString(); JsonObject patchObj = stringToJson(jsonpatch); @@ -831,29 +838,29 @@ public class FirewallConfigPolicy extends Policy { /* * Inserting firewallRuleList data into the Terms, SecurityZone, and Action tables */ - for(int ri = 0; ri < firewallRules.size(); ri++) { + for (int ri = 0; ri < firewallRules.size(); ri++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject ruleListobj = firewallRules.getJsonObject(ri); - //get values from JSON fields of firewallRulesList Array + // get values from JSON fields of firewallRulesList Array String ruleName = ruleListobj.get("ruleName").toString().replace('"', '\''); String action = ruleListobj.get("action").toString().replace('"', '\''); String description = ruleListobj.get("description").toString().replace('"', '\''); List<Object> result = dbConnection.getDataById(TermList.class, "termName", ruleName); - if(result != null && !result.isEmpty()){ + if (result != null && !result.isEmpty()) { TermList termEntry = (TermList) result.get(0); dbConnection.delete(termEntry); } - //getting fromZone Array field from the firewallRulesList + // getting fromZone Array field from the firewallRulesList JsonArray fromZoneArray = ruleListobj.getJsonArray("fromZones"); String fromZoneString = null; - for (int fromZoneIndex = 0; fromZoneIndex<fromZoneArray.size() ; fromZoneIndex++) { + for (int fromZoneIndex = 0; fromZoneIndex < fromZoneArray.size(); fromZoneIndex++) { String value = fromZoneArray.get(fromZoneIndex).toString(); value = value.replace("\"", ""); @@ -865,13 +872,12 @@ public class FirewallConfigPolicy extends Policy { } } - String fromZoneInsert = "'"+fromZoneString+"'"; + String fromZoneInsert = "'" + fromZoneString + "'"; - //getting toZone Array field from the firewallRulesList + // getting toZone Array field from the firewallRulesList JsonArray toZoneArray = ruleListobj.getJsonArray("toZones"); String toZoneString = null; - for (int toZoneIndex = 0; toZoneIndex < toZoneArray.size(); toZoneIndex++) { String value = toZoneArray.get(toZoneIndex).toString(); value = value.replace("\"", ""); @@ -884,18 +890,18 @@ public class FirewallConfigPolicy extends Policy { } } - String toZoneInsert = "'"+toZoneString+"'"; - //getting sourceList Array fields from the firewallRulesList + String toZoneInsert = "'" + toZoneString + "'"; + // getting sourceList Array fields from the firewallRulesList JsonArray srcListArray = ruleListobj.getJsonArray("sourceList"); String srcListString = null; - for (int srcListIndex = 0; srcListIndex<srcListArray.size(); srcListIndex++) { + for (int srcListIndex = 0; srcListIndex < srcListArray.size(); srcListIndex++) { JsonObject srcListObj = srcListArray.getJsonObject(srcListIndex); String type = srcListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = srcListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = srcListObj.get("value").toString(); @@ -904,19 +910,19 @@ public class FirewallConfigPolicy extends Policy { srcListString = getLeftOrRight(srcListString, value); } - String srcListInsert = "'"+srcListString+"'"; + String srcListInsert = "'" + srcListString + "'"; - //getting destinationList Array fields from the firewallRulesList + // getting destinationList Array fields from the firewallRulesList JsonArray destListArray = ruleListobj.getJsonArray("destinationList"); String destListString = null; - for (int destListIndex = 0; destListIndex<destListArray.size(); destListIndex ++) { + for (int destListIndex = 0; destListIndex < destListArray.size(); destListIndex++) { JsonObject destListObj = destListArray.getJsonObject(destListIndex); String type = destListObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destListObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destListObj.get("value").toString(); @@ -924,19 +930,20 @@ public class FirewallConfigPolicy extends Policy { destListString = getLeftOrRight(destListString, value); } - String destListInsert = "'"+destListString+"'"; + String destListInsert = "'" + destListString + "'"; - //getting destServices Array fields from the firewallRulesList + // getting destServices Array fields from the firewallRulesList JsonArray destServicesArray = ruleListobj.getJsonArray("destServices"); String destPortListString = null; - for (int destPortListIndex = 0; destPortListIndex < destServicesArray.size(); destPortListIndex++) { + for (int destPortListIndex = 0; destPortListIndex < destServicesArray + .size(); destPortListIndex++) { JsonObject destServicesObj = destServicesArray.getJsonObject(destPortListIndex); String type = destServicesObj.get("type").toString().replace("\"", ""); String value = null; - if(type.equals("REFERENCE")||type.equals("GROUP")){ + if (type.equals("REFERENCE") || type.equals("GROUP")) { value = destServicesObj.get("name").toString(); - } else if (type.equalsIgnoreCase("ANY")){ + } else if (type.equalsIgnoreCase("ANY")) { value = null; } else { value = destServicesObj.get("value").toString(); @@ -944,7 +951,7 @@ public class FirewallConfigPolicy extends Policy { destPortListString = getLeftOrRight(destPortListString, value); } - String destPortListInsert = "'"+destPortListString+"'"; + String destPortListInsert = "'" + destPortListString + "'"; /* * Create Queries to INSERT data into database tables and execute @@ -968,8 +975,9 @@ public class FirewallConfigPolicy extends Policy { termEntry.setUserCreatedBy(userInfo); dbConnection.save(termEntry); - List<Object> actionResult = dbConnection.getDataById(ActionList.class, "actionName", action); - if(actionResult == null || actionResult.isEmpty()){ + List<Object> actionResult = + dbConnection.getDataById(ActionList.class, "actionName", action); + if (actionResult == null || actionResult.isEmpty()) { saveActionListToDb(dbConnection, action); } } @@ -977,61 +985,66 @@ public class FirewallConfigPolicy extends Policy { if (path.contains("serviceGroups")) { /* - * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList tables + * Inserting serviceGroups data into the ServiceGroup, ServiceList, ProtocolList, and PortList + * tables */ - for(int si = 0; si < serviceGroup.size(); si++) { + for (int si = 0; si < serviceGroup.size(); si++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject svcGroupListobj = serviceGroup.getJsonObject(si); String groupName = svcGroupListobj.get("name").toString().replace('"', '\''); String description = null; - if (svcGroupListobj.containsKey("description")){ + if (svcGroupListobj.containsKey("description")) { description = svcGroupListobj.get("description").toString().replace('"', '\''); } JsonArray membersArray = svcGroupListobj.getJsonArray("members"); Boolean isServiceGroup = false; - if (membersArray!=null){ + if (membersArray != null) { String membersType = membersArray.getJsonObject(0).get("type").toString(); if (membersType.contains("REFERENCE")) { isServiceGroup = true; } } - //Insert values into GROUPSERVICELIST table if name begins with Group + // Insert values into GROUPSERVICELIST table if name begins with Group if (isServiceGroup) { - List<Object> result = dbConnection.getDataById(GroupServiceList.class, "name", groupName); - if(result != null && !result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(GroupServiceList.class, "name", groupName); + if (result != null && !result.isEmpty()) { GroupServiceList groupEntry = (GroupServiceList) result.get(0); dbConnection.delete(groupEntry); } saveGroupServiceListTableToDb(dbConnection, groupName, membersArray); - } else { //Insert JSON data serviceGroup table, protocollist table, and portlist table + } else { // Insert JSON data serviceGroup table, protocollist table, and portlist table String type = svcGroupListobj.get("type").toString().replace('"', '\''); - String transportProtocol = svcGroupListobj.get("transportProtocol").toString().replace('"', '\''); + String transportProtocol = + svcGroupListobj.get("transportProtocol").toString().replace('"', '\''); String ports = svcGroupListobj.get("ports").toString().replace('"', '\''); List<Object> result = dbConnection.getDataById(ServiceList.class, "name", groupName); - if(result != null && !result.isEmpty()){ + if (result != null && !result.isEmpty()) { ServiceList serviceEntry = (ServiceList) result.get(0); dbConnection.delete(serviceEntry); } - saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, ports); + saveServiceListToDb(dbConnection, groupName, description, type, transportProtocol, + ports); - List<Object> protocolResult = dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol); - if(protocolResult == null || protocolResult.isEmpty()){ + List<Object> protocolResult = + dbConnection.getDataById(ProtocolList.class, "protocolName", transportProtocol); + if (protocolResult == null || protocolResult.isEmpty()) { saveProtocolListToDb(dbConnection, transportProtocol); } List<Object> portResult = dbConnection.getDataById(PortList.class, "portName", ports); - if(portResult == null || portResult.isEmpty()){ + if (portResult == null || portResult.isEmpty()) { savePortListToDb(dbConnection, ports); } } @@ -1042,46 +1055,47 @@ public class FirewallConfigPolicy extends Policy { /* * Inserting addressGroup data into the ADDRESSGROUP table */ - for(int ai=0; ai < addressGroup.size() ; ai++) { + for (int ai = 0; ai < addressGroup.size(); ai++) { /* * Populate ArrayLists with values from the JSON */ - //create the JSON object from the JSON Array for each iteration through the for loop + // create the JSON object from the JSON Array for each iteration through the for loop JsonObject addressGroupObj = addressGroup.getJsonObject(ai); - //create JSON array for members + // create JSON array for members JsonArray membersArray = addressGroupObj.getJsonArray("members"); String addressGroupName = addressGroupObj.get("name").toString().replace('"', '\''); String description = null; - if (addressGroupObj.containsKey("description")){ + if (addressGroupObj.containsKey("description")) { description = addressGroupObj.get("description").toString().replace('"', '\''); } String prefixIP = null; String type = null; - for (int membersIndex=0; membersIndex < membersArray.size(); membersIndex++) { + for (int membersIndex = 0; membersIndex < membersArray.size(); membersIndex++) { JsonObject membersObj = membersArray.getJsonObject(membersIndex); type = membersObj.get("type").toString().replace("\"", ""); - String value = null; prefixIP = getName(prefixIP, membersObj, type); } - String prefixList = "'"+prefixIP+"'"; + String prefixList = "'" + prefixIP + "'"; Boolean isAddressGroup = type.contains("REFERENCE"); if (isAddressGroup) { - List<Object> result = dbConnection.getDataById(AddressGroup.class, "name", addressGroupName); - if(result != null && !result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(AddressGroup.class, "name", addressGroupName); + if (result != null && !result.isEmpty()) { AddressGroup addressGroupEntry = (AddressGroup) result.get(0); dbConnection.delete(addressGroupEntry); } saveAddressGroupToDb(dbConnection, addressGroupName, description, prefixList); } else { - List<Object> result = dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName); - if(result != null && !result.isEmpty()){ + List<Object> result = + dbConnection.getDataById(PrefixList.class, "prefixListName", addressGroupName); + if (result != null && !result.isEmpty()) { PrefixList prefixListEntry = (PrefixList) result.get(0); dbConnection.delete(prefixListEntry); } @@ -1091,8 +1105,9 @@ public class FirewallConfigPolicy extends Policy { } } removeDuplicateValuesFromLookup(dbConnection); - }catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", "Exception executing Firewall queries"); + } catch (Exception e) { + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, "FirewallConfigPolicy", + "Exception executing Firewall queries"); return false; } return true; @@ -1123,7 +1138,8 @@ public class FirewallConfigPolicy extends Policy { dbConnection.save(protocolEntry); } - private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, String transportProtocol, String ports) { + private void saveServiceListToDb(CommonClassDaoImpl dbConnection, String groupName, String description, String type, + String transportProtocol, String ports) { ServiceList serviceListEntry = new ServiceList(); serviceListEntry.setServiceName(groupName); serviceListEntry.setServiceDescription(description); @@ -1134,7 +1150,8 @@ public class FirewallConfigPolicy extends Policy { dbConnection.save(serviceListEntry); } - private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) { + private void savePrefixListToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, + String prefixList) { PrefixList newPrefixList = new PrefixList(); newPrefixList.setPrefixListName(addressGroupName); newPrefixList.setDescription(description); @@ -1142,7 +1159,8 @@ public class FirewallConfigPolicy extends Policy { dbConnection.save(newPrefixList); } - private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, String prefixList) { + private void saveAddressGroupToDb(CommonClassDaoImpl dbConnection, String addressGroupName, String description, + String prefixList) { AddressGroup newAddressGroup = new AddressGroup(); newAddressGroup.setGroupName(addressGroupName); newAddressGroup.setDescription(description); @@ -1151,7 +1169,7 @@ public class FirewallConfigPolicy extends Policy { } private JsonObject stringToJson(String jsonString) { - //Read jsonBody to JsonObject + // Read jsonBody to JsonObject StringReader in = new StringReader(jsonString); JsonReader jsonReader = Json.createReader(in); JsonObject json = jsonReader.readObject(); @@ -1167,7 +1185,7 @@ public class FirewallConfigPolicy extends Policy { oldJason = JsonLoader.fromString(oldJson); updatedJason = JsonLoader.fromString(json); } catch (IOException e) { - LOGGER.error("Exception Occured"+e); + LOGGER.error("Exception Occured" + e); } return JsonDiff.asJson(oldJason, updatedJason); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java index fc08b643e..f565254f1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotifications.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileWriter; @@ -34,7 +35,9 @@ import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; import java.util.List; + import javax.persistence.PersistenceException; + import org.apache.commons.io.FilenameUtils; import org.hibernate.Query; import org.hibernate.Session; @@ -70,7 +73,6 @@ public class HandleIncomingNotifications { public static final String OTHER_CONFIG = "OTHER"; public static final String AUDIT_USER = "audit"; - private static SessionFactory sessionfactory; @Autowired diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java index 26c7ed834..5120d25fa 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/MicroServiceConfigPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -20,6 +20,12 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; + import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -33,22 +39,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.MicroServiceModels; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -61,7 +51,17 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.MicroServiceModels; public class MicroServiceConfigPolicy extends Policy { @@ -70,7 +70,7 @@ public class MicroServiceConfigPolicy extends Policy { private static Map<String, String> mapAttribute = new HashMap<>(); private static Map<String, String> mapMatch = new HashMap<>(); - private static synchronized Map<String, String> getMatchMap () { + private static synchronized Map<String, String> getMatchMap() { return mapMatch; } @@ -82,34 +82,33 @@ public class MicroServiceConfigPolicy extends Policy { super(); } - public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter){ + public MicroServiceConfigPolicy(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, String jsonBody) { - if(policyName.endsWith(".xml")){ - policyName = policyName.replace(".xml", ""); - } - try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json")){ + if (policyName.endsWith(".xml")) { + policyName = policyName.replace(".xml", ""); + } + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json")) { out.println(jsonBody); } catch (Exception e) { - LOGGER.error("Exception Occured While writing Configuration data"+e); + LOGGER.error("Exception Occured While writing Configuration data" + e); } } - @Override public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ - //Prep and configure the policy for saving + if (!isPreparedToSave()) { + // Prep and configure the policy for saving prepareToSave(); } @@ -117,18 +116,18 @@ public class MicroServiceConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -156,7 +155,6 @@ public class MicroServiceConfigPolicy extends Policy { policyName = policyName + ".xml"; } - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); configPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -170,32 +168,33 @@ public class MicroServiceConfigPolicy extends Policy { name = fileName.substring(fileName.lastIndexOf("/") + 1, fileName.length()); } - //setup values for pulling out matching attributes + // setup values for pulling out matching attributes ObjectMapper mapper = new ObjectMapper(); String matching = null; Map<String, String> matchMap = null; try { JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody()); - if (policyAdapter.getTtlDate()==null){ + if (policyAdapter.getTtlDate() == null) { policyAdapter.setTtlDate("NA"); } - if (policyAdapter.getServiceType().contains("-v")){ + if (policyAdapter.getServiceType().contains("-v")) { matching = getValueFromDictionary(policyAdapter.getServiceType()); } else { - String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""}); + String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), + new String[] {"\""}, new String[] {""}); matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion); } - if (matching != null && !matching.isEmpty()){ + if (matching != null && !matching.isEmpty()) { matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching); - setMatchMap(matchMap); - if(policyAdapter.getJsonBody() != null){ - pullMatchValue(rootNode); + setMatchMap(matchMap); + if (policyAdapter.getJsonBody() != null) { + pullMatchValue(rootNode); } } } catch (IOException e1) { throw new PAPException(e1); } - + // Match for policyName allOfOne.getMatch().add(createMatch("PolicyName", name)); @@ -203,7 +202,7 @@ public class MicroServiceConfigPolicy extends Policy { // Adding the matches to AllOfType element Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); - if (matchMap==null || matchMap.isEmpty()){ + if (matchMap == null || matchMap.isEmpty()) { // Match for ConfigName allOf.getMatch().add(createMatch("ConfigName", policyAdapter.getConfigName())); // Match for Service @@ -212,29 +211,25 @@ public class MicroServiceConfigPolicy extends Policy { allOf.getMatch().add(createDynamicMatch("uuid", policyAdapter.getUuid())); // Match for location allOf.getMatch().add(createDynamicMatch("location", policyAdapter.getLocation())); - }else { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + } else { + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true")){ - if (mapAttribute.containsKey(key)){ + if (value.contains("matching-true")) { + if (mapAttribute.containsKey(key)) { allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key))); } } } } // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); @@ -265,7 +260,8 @@ public class MicroServiceConfigPolicy extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -284,7 +280,8 @@ public class MicroServiceConfigPolicy extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "MicroServiceConfigPolicy", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); @@ -317,34 +314,36 @@ public class MicroServiceConfigPolicy extends Policy { private void pullMatchValue(JsonNode rootNode) { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); String newValue = null; - while (fieldsIterator.hasNext()) { - Map.Entry<String, JsonNode> field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value.isContainerNode() && !value.isArray()) { - pullMatchValue(value); // RECURSIVE CALL - } else { - newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); - mapAttribute.put(key, newValue); - } - } - - } - - private String getValueFromDictionary(String service){ - String ruleTemplate=null; - String modelName = service.split("-v")[0]; - String modelVersion = service.split("-v")[1]; - - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List<Object> result = dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName+":"+modelVersion); - if(result != null && !result.isEmpty()){ - MicroServiceModels model = (MicroServiceModels) result.get(0); - ruleTemplate = model.getAnnotation(); - } - return ruleTemplate; - } - + while (fieldsIterator.hasNext()) { + Map.Entry<String, JsonNode> field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullMatchValue(value); // RECURSIVE CALL + } else { + newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""}, + new String[] {"", "", ""}); + mapAttribute.put(key, newValue); + } + } + + } + + private String getValueFromDictionary(String service) { + String ruleTemplate = null; + String modelName = service.split("-v")[0]; + String modelVersion = service.split("-v")[1]; + + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List<Object> result = + dbConnection.getDataById(MicroServiceModels.class, "modelName:version", modelName + ":" + modelVersion); + if (result != null && !result.isEmpty()) { + MicroServiceModels model = (MicroServiceModels) result.get(0); + ruleTemplate = model.getAnnotation(); + } + return ruleTemplate; + } + // Data required for Advice part is setting here. private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { AdviceExpressionsType advices = new AdviceExpressionsType(); @@ -372,12 +371,12 @@ public class MicroServiceConfigPolicy extends Policy { AttributeValueType AttributeValue = new AttributeValueType(); AttributeValue.setDataType(URI_DATATYPE); String configName; - if(policyName.endsWith(".xml")){ + if (policyName.endsWith(".xml")) { configName = policyName.replace(".xml", ""); - }else{ + } else { configName = policyName; } - String content = CONFIG_URL +"/Config/" + configName + ".json"; + String content = CONFIG_URL + "/Config/" + configName + ".json"; AttributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(AttributeValue)); @@ -427,16 +426,16 @@ public class MicroServiceConfigPolicy extends Policy { assignment7.setAttributeId("matching:service"); assignment7.setCategory(CATEGORY_RESOURCE); assignment7.setIssuer(""); - + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); configNameAttributeValue7.setDataType(STRING_DATATYPE); configNameAttributeValue7.getContent().add(policyAdapter.getServiceType()); assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - + advice.getAttributeAssignmentExpression().add(assignment7); Map<String, String> matchMap = getMatchMap(); - if (matchMap==null || matchMap.isEmpty()){ + if (matchMap == null || matchMap.isEmpty()) { AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType(); assignment6.setAttributeId("matching:" + CONFIGID); assignment6.setCategory(CATEGORY_RESOURCE); @@ -449,7 +448,6 @@ public class MicroServiceConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment6); - AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType(); assignment8.setAttributeId("matching:uuid"); assignment8.setCategory(CATEGORY_RESOURCE); @@ -474,28 +472,28 @@ public class MicroServiceConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment9); } else { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true")){ - if (mapAttribute.containsKey(key)){ + if (value.contains("matching-true")) { + if (mapAttribute.containsKey(key)) { AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); assignment9.setAttributeId("matching:" + key); assignment9.setCategory(CATEGORY_RESOURCE); assignment9.setIssuer(""); - + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); configNameAttributeValue9.setDataType(STRING_DATATYPE); configNameAttributeValue9.getContent().add(mapAttribute.get(key)); assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - + advice.getAttributeAssignmentExpression().add(assignment9); - + } } } } - + AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); assignment10.setAttributeId("Priority"); assignment10.setCategory(CATEGORY_RESOURCE); @@ -508,7 +506,7 @@ public class MicroServiceConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment10); - //Risk Attributes + // Risk Attributes AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); assignment11.setAttributeId("RiskType"); assignment11.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java index 2e2a74015..34dd73c57 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/NotifyOtherPaps.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.util.XACMLProperties; + import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; @@ -31,6 +32,7 @@ import java.util.Base64; import java.util.LinkedList; import java.util.List; import java.util.UUID; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.XACMLRestProperties; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java index 2719a155b..82a6c4b83 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -20,6 +20,12 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Splitter; + import java.io.File; import java.io.IOException; import java.io.PrintWriter; @@ -33,22 +39,6 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.StringUtils; -import org.onap.policy.common.logging.eelf.MessageCodes; -import org.onap.policy.common.logging.eelf.PolicyLogger; -import org.onap.policy.common.logging.flexlogger.FlexLogger; -import org.onap.policy.common.logging.flexlogger.Logger; -import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; -import org.onap.policy.rest.adapter.PolicyRestAdapter; -import org.onap.policy.rest.jpa.OptimizationModels; - -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Splitter; - import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; @@ -61,7 +51,17 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.ObjectFactory; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang.StringUtils; +import org.onap.policy.common.logging.eelf.MessageCodes; +import org.onap.policy.common.logging.eelf.PolicyLogger; +import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.onap.policy.common.logging.flexlogger.Logger; +import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; +import org.onap.policy.rest.adapter.PolicyRestAdapter; +import org.onap.policy.rest.jpa.OptimizationModels; public class OptimizationConfigPolicy extends Policy { @@ -70,7 +70,7 @@ public class OptimizationConfigPolicy extends Policy { private static Map<String, String> mapAttribute = new HashMap<>(); private static Map<String, String> mapMatch = new HashMap<>(); - private static synchronized Map<String, String> getMatchMap () { + private static synchronized Map<String, String> getMatchMap() { return mapMatch; } @@ -82,36 +82,35 @@ public class OptimizationConfigPolicy extends Policy { super(); } - public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter){ + public OptimizationConfigPolicy(PolicyRestAdapter policyAdapter) { this.policyAdapter = policyAdapter; } - //save configuration of the policy based on the policyname + // save configuration of the policy based on the policyname private void saveConfigurations(String policyName, String jsonBody) { - if(policyName.endsWith(".xml")){ + if (policyName.endsWith(".xml")) { policyName = policyName.replace(".xml", ""); } - try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName +".json");){ + try (PrintWriter out = new PrintWriter(CONFIG_HOME + File.separator + policyName + ".json");) { out.println(jsonBody); } catch (Exception e) { - LOGGER.error("Exception Occured While writing Configuration data"+e); + LOGGER.error("Exception Occured While writing Configuration data" + e); } } - @Override public Map<String, String> savePolicies() throws PAPException { Map<String, String> successMap = new HashMap<>(); - if(isPolicyExists()){ + if (isPolicyExists()) { successMap.put("EXISTS", "This Policy already exist on the PAP"); return successMap; } - if(!isPreparedToSave()){ - //Prep and configure the policy for saving + if (!isPreparedToSave()) { + // Prep and configure the policy for saving prepareToSave(); } @@ -119,18 +118,18 @@ public class OptimizationConfigPolicy extends Policy { Path newPolicyPath = null; newPolicyPath = Paths.get(policyAdapter.getNewFileName()); - successMap = createPolicy(newPolicyPath,getCorrectPolicyDataObject()); + successMap = createPolicy(newPolicyPath, getCorrectPolicyDataObject()); return successMap; } - //This is the method for preparing the policy for saving. We have broken it out - //separately because the fully configured policy is used for multiple things + // This is the method for preparing the policy for saving. We have broken it out + // separately because the fully configured policy is used for multiple things @Override - public boolean prepareToSave() throws PAPException{ + public boolean prepareToSave() throws PAPException { - if(isPreparedToSave()){ - //we have already done this + if (isPreparedToSave()) { + // we have already done this return true; } @@ -158,7 +157,6 @@ public class OptimizationConfigPolicy extends Policy { policyName = policyName + ".xml"; } - PolicyType configPolicy = (PolicyType) policyAdapter.getData(); configPolicy.setDescription(policyAdapter.getPolicyDescription()); @@ -172,32 +170,33 @@ public class OptimizationConfigPolicy extends Policy { name = fileName.substring(fileName.lastIndexOf('/') + 1, fileName.length()); } - //setup values for pulling out matching attributes + // setup values for pulling out matching attributes ObjectMapper mapper = new ObjectMapper(); String matching = null; Map<String, String> matchMap = null; try { JsonNode rootNode = mapper.readTree(policyAdapter.getJsonBody()); - if (policyAdapter.getTtlDate()==null){ + if (policyAdapter.getTtlDate() == null) { policyAdapter.setTtlDate("NA"); } - if (policyAdapter.getServiceType().contains("-v")){ + if (policyAdapter.getServiceType().contains("-v")) { matching = getValueFromDictionary(policyAdapter.getServiceType()); } else { - String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), new String[]{"\""}, new String[]{""}); + String jsonVersion = StringUtils.replaceEach(rootNode.get("version").toString(), + new String[] {"\""}, new String[] {""}); matching = getValueFromDictionary(policyAdapter.getServiceType() + "-v" + jsonVersion); } - if (matching != null && !matching.isEmpty()){ + if (matching != null && !matching.isEmpty()) { matchMap = Splitter.on(",").withKeyValueSeparator("=").split(matching); setMatchMap(matchMap); - if(policyAdapter.getJsonBody() != null){ - pullMatchValue(rootNode); + if (policyAdapter.getJsonBody() != null) { + pullMatchValue(rootNode); } } } catch (IOException e1) { throw new PAPException(e1); } - + // Match for policyName allOfOne.getMatch().add(createMatch("PolicyName", name)); @@ -205,28 +204,24 @@ public class OptimizationConfigPolicy extends Policy { // Adding the matches to AllOfType element Match for Onap allOf.getMatch().add(createMatch("ONAPName", policyAdapter.getOnapName())); - if (matchMap!=null && !matchMap.isEmpty()) { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + if (matchMap != null && !matchMap.isEmpty()) { + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true") && mapAttribute.containsKey(key)){ + if (value.contains("matching-true") && mapAttribute.containsKey(key)) { allOf.getMatch().add(createDynamicMatch(key, mapAttribute.get(key))); } } } // Match for riskType - allOf.getMatch().add( - createDynamicMatch("RiskType", policyAdapter.getRiskType())); + allOf.getMatch().add(createDynamicMatch("RiskType", policyAdapter.getRiskType())); // Match for riskLevel - allOf.getMatch().add( - createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); + allOf.getMatch().add(createDynamicMatch("RiskLevel", String.valueOf(policyAdapter.getRiskLevel()))); // Match for riskguard - allOf.getMatch().add( - createDynamicMatch("guard", policyAdapter.getGuard())); + allOf.getMatch().add(createDynamicMatch("guard", policyAdapter.getGuard())); // Match for ttlDate - allOf.getMatch().add( - createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); + allOf.getMatch().add(createDynamicMatch("TTLDate", policyAdapter.getTtlDate())); AnyOfType anyOf = new AnyOfType(); anyOf.getAllOf().add(allOfOne); @@ -257,7 +252,8 @@ public class OptimizationConfigPolicy extends Policy { try { accessURI = new URI(ACTION_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating ACCESS URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", + "Exception creating ACCESS URI"); } accessAttributeDesignator.setCategory(CATEGORY_ACTION); accessAttributeDesignator.setDataType(STRING_DATATYPE); @@ -276,7 +272,8 @@ public class OptimizationConfigPolicy extends Policy { try { configURI = new URI(RESOURCE_ID); } catch (URISyntaxException e) { - PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", "Exception creating Config URI"); + PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE, e, "OptimizationConfigPolicy", + "Exception creating Config URI"); } configAttributeDesignator.setCategory(CATEGORY_RESOURCE); configAttributeDesignator.setDataType(STRING_DATATYPE); @@ -309,34 +306,36 @@ public class OptimizationConfigPolicy extends Policy { private void pullMatchValue(JsonNode rootNode) { Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields(); String newValue = null; - while (fieldsIterator.hasNext()) { - Map.Entry<String, JsonNode> field = fieldsIterator.next(); - final String key = field.getKey(); - final JsonNode value = field.getValue(); - if (value.isContainerNode() && !value.isArray()) { - pullMatchValue(value); // RECURSIVE CALL - } else { - newValue = StringUtils.replaceEach(value.toString(), new String[]{"[", "]", "\""}, new String[]{"", "", ""}); - mapAttribute.put(key, newValue); - } - } - - } - - private String getValueFromDictionary(String service){ - String ruleTemplate=null; - String modelName = service.split("-v")[0]; - String modelVersion = service.split("-v")[1]; - - CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); - List<Object> result = dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName+":"+modelVersion); - if(result != null && !result.isEmpty()){ - OptimizationModels model = (OptimizationModels) result.get(0); - ruleTemplate = model.getAnnotation(); - } - return ruleTemplate; - } - + while (fieldsIterator.hasNext()) { + Map.Entry<String, JsonNode> field = fieldsIterator.next(); + final String key = field.getKey(); + final JsonNode value = field.getValue(); + if (value.isContainerNode() && !value.isArray()) { + pullMatchValue(value); // RECURSIVE CALL + } else { + newValue = StringUtils.replaceEach(value.toString(), new String[] {"[", "]", "\""}, + new String[] {"", "", ""}); + mapAttribute.put(key, newValue); + } + } + + } + + private String getValueFromDictionary(String service) { + String ruleTemplate = null; + String modelName = service.split("-v")[0]; + String modelVersion = service.split("-v")[1]; + + CommonClassDaoImpl dbConnection = new CommonClassDaoImpl(); + List<Object> result = + dbConnection.getDataById(OptimizationModels.class, "modelName:version", modelName + ":" + modelVersion); + if (result != null && !result.isEmpty()) { + OptimizationModels model = (OptimizationModels) result.get(0); + ruleTemplate = model.getAnnotation(); + } + return ruleTemplate; + } + // Data required for Advice part is setting here. private AdviceExpressionsType getAdviceExpressions(int version, String fileName) { AdviceExpressionsType advices = new AdviceExpressionsType(); @@ -366,18 +365,18 @@ public class OptimizationConfigPolicy extends Policy { AttributeValueType attributeValue = new AttributeValueType(); attributeValue.setDataType(URI_DATATYPE); String configName; - if(policyName.endsWith(".xml")){ + if (policyName.endsWith(".xml")) { configName = policyName.replace(".xml", ""); - }else{ + } else { configName = policyName; } - String content = CONFIG_URL +"/Config/" + configName + ".json"; + String content = CONFIG_URL + "/Config/" + configName + ".json"; attributeValue.getContent().add(content); assignment2.setExpression(new ObjectFactory().createAttributeValue(attributeValue)); advice.getAttributeAssignmentExpression().add(assignment2); - //PolicyName Attribute Assignment + // PolicyName Attribute Assignment AttributeAssignmentExpressionType assignment3 = new AttributeAssignmentExpressionType(); assignment3.setAttributeId("PolicyName"); assignment3.setCategory(CATEGORY_RESOURCE); @@ -395,7 +394,7 @@ public class OptimizationConfigPolicy extends Policy { assignment3.setExpression(new ObjectFactory().createAttributeValue(attributeValue3)); advice.getAttributeAssignmentExpression().add(assignment3); - //VersionNumber Attribute Assignment + // VersionNumber Attribute Assignment AttributeAssignmentExpressionType assignment4 = new AttributeAssignmentExpressionType(); assignment4.setAttributeId("VersionNumber"); assignment4.setCategory(CATEGORY_RESOURCE); @@ -408,7 +407,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment4); - //OnapName Attribute Assignment + // OnapName Attribute Assignment AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType(); assignment5.setAttributeId("matching:" + ONAPID); assignment5.setCategory(CATEGORY_RESOURCE); @@ -421,41 +420,41 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment5); - //ServiceType Attribute Assignment + // ServiceType Attribute Assignment AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType(); assignment7.setAttributeId("matching:service"); assignment7.setCategory(CATEGORY_RESOURCE); assignment7.setIssuer(""); - + AttributeValueType configNameAttributeValue7 = new AttributeValueType(); configNameAttributeValue7.setDataType(STRING_DATATYPE); configNameAttributeValue7.getContent().add(policyAdapter.getServiceType()); assignment7.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue7)); - + advice.getAttributeAssignmentExpression().add(assignment7); // Add matching attribute assignments if exist Map<String, String> matchMap = getMatchMap(); - if (matchMap!=null && !matchMap.isEmpty()) { - for (Entry<String, String> matchValue : matchMap.entrySet()){ + if (matchMap != null && !matchMap.isEmpty()) { + for (Entry<String, String> matchValue : matchMap.entrySet()) { String value = matchValue.getValue(); String key = matchValue.getKey().trim(); - if (value.contains("matching-true") && mapAttribute.containsKey(key)){ + if (value.contains("matching-true") && mapAttribute.containsKey(key)) { AttributeAssignmentExpressionType assignment9 = new AttributeAssignmentExpressionType(); assignment9.setAttributeId("matching:" + key); assignment9.setCategory(CATEGORY_RESOURCE); assignment9.setIssuer(""); - + AttributeValueType configNameAttributeValue9 = new AttributeValueType(); configNameAttributeValue9.setDataType(STRING_DATATYPE); configNameAttributeValue9.getContent().add(mapAttribute.get(key)); assignment9.setExpression(new ObjectFactory().createAttributeValue(configNameAttributeValue9)); - + advice.getAttributeAssignmentExpression().add(assignment9); } } } - + // Priority Attribute Assignment AttributeAssignmentExpressionType assignment10 = new AttributeAssignmentExpressionType(); assignment10.setAttributeId("Priority"); @@ -469,7 +468,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment10); - //RiskType Attribute Assignment + // RiskType Attribute Assignment AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType(); assignment11.setAttributeId("RiskType"); assignment11.setCategory(CATEGORY_RESOURCE); @@ -482,7 +481,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment11); - //RiskLevel Attribute Assignment + // RiskLevel Attribute Assignment AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType(); assignment12.setAttributeId("RiskLevel"); assignment12.setCategory(CATEGORY_RESOURCE); @@ -495,7 +494,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment12); - //Guard Attribute Assignment + // Guard Attribute Assignment AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType(); assignment13.setAttributeId("guard"); assignment13.setCategory(CATEGORY_RESOURCE); @@ -508,7 +507,7 @@ public class OptimizationConfigPolicy extends Policy { advice.getAttributeAssignmentExpression().add(assignment13); - //TTLDate Attribute Assignment + // TTLDate Attribute Assignment AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType(); assignment14.setAttributeId("TTLDate"); assignment14.setCategory(CATEGORY_RESOURCE); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java index 549d26b28..278e1e866 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/Policy.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * Modified Copyright (C) 2018 Samsung Electronics Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); @@ -21,6 +21,12 @@ package org.onap.policy.pap.xacml.rest.components; +import com.att.research.xacml.api.pap.PAPException; +import com.att.research.xacml.std.IdentifierImpl; +import com.att.research.xacml.util.XACMLProperties; +import com.att.research.xacmlatt.pdp.policy.PolicyDef; +import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; + import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -30,6 +36,13 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; + +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; +import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + import org.apache.commons.io.FilenameUtils; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -38,16 +51,6 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.XACMLRestProperties; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.xacml.util.XACMLPolicyWriter; -import com.att.research.xacml.api.pap.PAPException; -import com.att.research.xacml.std.IdentifierImpl; -import com.att.research.xacml.util.XACMLProperties; -import com.att.research.xacmlatt.pdp.policy.PolicyDef; -import com.att.research.xacmlatt.pdp.policy.dom.DOMPolicyDef; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; public abstract class Policy { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java index 9a39b6ed1..25c900393 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDao.java @@ -24,6 +24,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.ByteArrayInputStream; import java.io.InputStream; import java.net.URI; @@ -36,7 +37,9 @@ import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; + import javax.persistence.PersistenceException; + import org.apache.commons.io.FilenameUtils; import org.hibernate.Criteria; import org.hibernate.LockMode; @@ -86,15 +89,12 @@ public class PolicyDBDao { public static final String PDPENTITY_SELECT = "SELECT p FROM PdpEntity p WHERE p.pdpId=:pdpId AND p.deleted=:deleted"; public static final String GROUP_NOT_FOUND = "The group could not be found with id "; - public static final String FOUND_IN_DB_NOT_DEL = - " were found in the database that are not deleted"; + public static final String FOUND_IN_DB_NOT_DEL = " were found in the database that are not deleted"; public static final String MORE_THAN_ONE_PDP = "Somehow, more than one pdp with the same id "; - public static final String DELETED_STATUS_FOUND = - " and deleted status were found in the database"; + public static final String DELETED_STATUS_FOUND = " and deleted status were found in the database"; public static final String DUPLICATE_GROUPID = "Somehow, more than one group with the same id "; public static final String PDP_ID = "pdpId"; - public static final String QUERY_FAILED_FOR_GROUP = - "Query failed trying to check for existing group"; + public static final String QUERY_FAILED_FOR_GROUP = "Query failed trying to check for existing group"; public static final String QUERY_FAILED_GET_GROUP = "Query failed trying to get group "; public static final String SCOPE = "scope"; public static final String POLICYDBDAO_VAR = "PolicyDBDao"; @@ -106,7 +106,6 @@ public class PolicyDBDao { private List<?> otherServers; private PAPPolicyEngine papEngine; - /** * Gets the current instance of PolicyDBDao. * @@ -140,8 +139,8 @@ public class PolicyDBDao { public PolicyDBDao(String init) { // not needed in this release if (!register()) { - PolicyLogger.error( - "This server's PolicyDBDao instance could not be registered and may not reveive updates"); + PolicyLogger + .error("This server's PolicyDBDao instance could not be registered and may not reveive updates"); } otherServers = getRemotePolicyDBDaoList(); @@ -157,17 +156,15 @@ public class PolicyDBDao { // waitTime in ms to wait for lock, or -1 to wait forever (no) @SuppressWarnings("deprecation") public void startTransactionSynced(Session session, int waitTime) { - logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " - + "\n startTransactionSynced(" + session + "," + waitTime + ") called\n\n"); + logger.debug("\n\nstartTransactionSynced(Hibernate Session,int waitTime) as " + "\n startTransactionSynced(" + + session + "," + waitTime + ") called\n\n"); DatabaseLockEntity lock = null; session.beginTransaction(); try { if (logger.isDebugEnabled()) { - logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" - + "\n\n"); + logger.debug("\n\nstartTransactionSynced():" + "\n ATTEMPT to get the DB lock" + "\n\n"); } - lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, - LockMode.PESSIMISTIC_WRITE); + lock = (DatabaseLockEntity) session.get(DatabaseLockEntity.class, 1, LockMode.PESSIMISTIC_WRITE); if (logger.isDebugEnabled()) { logger.debug("\n\nstartTransactionSynced():" + "\n GOT the DB lock" + "\n\n"); } @@ -201,8 +198,7 @@ public class PolicyDBDao { try { session.close(); } catch (Exception e) { - logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e); + logger.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); } } return policyDBDaoEntityList; @@ -222,11 +218,9 @@ public class PolicyDBDao { public PolicyDBDaoTransaction getNewAuditTransaction() { logger.debug("getNewAuditTransaction() as getNewAuditTransaction() called"); // Use the standard transaction wait time in ms - int auditWaitMs = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); + int auditWaitMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT)); // Use the (extended) audit timeout time in ms - int auditTimeoutMs = Integer - .parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); + int auditTimeoutMs = Integer.parseInt(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_AUDIT_TIMEOUT)); return new PolicyDbDaoTransactionInstance(auditTimeoutMs, auditWaitMs); } @@ -237,8 +231,7 @@ public class PolicyDBDao { * @param two A String or null to compare */ public static boolean stringEquals(String one, String two) { - logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two - + ") called"); + logger.debug("stringEquals(String one, String two) as stringEquals(" + one + ", " + two + ") called"); if (one == null && two == null) { return true; } @@ -272,8 +265,7 @@ public class PolicyDBDao { urlUserPass[2] = commaSplit[2]; } if (urlUserPass[1] == null || "".equals(urlUserPass[1])) { - String usernamePropertyValue = - XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); + String usernamePropertyValue = XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_USERID); if (usernamePropertyValue != null) { urlUserPass[1] = usernamePropertyValue; } @@ -332,8 +324,7 @@ public class PolicyDBDao { } } } - logger.debug( - "\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); + logger.debug("\nPolicyDBDao.register. Database locking and concurrency control is initialized\n"); PolicyDBDaoEntity foundPolicyDBDaoEntity = null; Criteria cr = session.createCriteria(PolicyDBDaoEntity.class); cr.add(Restrictions.eq("policyDBDaoUrl", url[0])); @@ -394,8 +385,8 @@ public class PolicyDBDao { * This method is called during all pushPolicy transactions and makes sure the file system group * is in sync with the database groupentity */ - public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, - GroupEntity groupentity) throws PAPException, PolicyDBException { + public StdPDPGroup synchronizeGroupPoliciesInFileSystem(StdPDPGroup pdpGroup, GroupEntity groupentity) + throws PAPException, PolicyDBException { HashMap<String, PDPPolicy> currentPolicyMap = new HashMap<>(); HashSet<String> newPolicyIdSet = new HashSet<>(); @@ -415,23 +406,19 @@ public class PolicyDBDao { // convert PolicyEntity object to PDPPolicy String name = pdpPolicyId.replace(".xml", ""); name = name.substring(0, name.lastIndexOf('.')); - InputStream policyStream = - new ByteArrayInputStream(policy.getPolicyData().getBytes()); + InputStream policyStream = new ByteArrayInputStream(policy.getPolicyData().getBytes()); pdpGroup.copyPolicyToFile(pdpPolicyId, name, policyStream); - URI location = - Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId) - .toUri(); + URI location = Paths.get(pdpGroup.getDirectory().toAbsolutePath().toString(), pdpPolicyId).toUri(); StdPDPPolicy newPolicy = null; try { newPolicy = new StdPDPPolicy(pdpPolicyId, true, removeExtensionAndVersionFromPolicyName(pdpPolicyId), location); newPolicySet.add(newPolicy); - logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() - + ", Location - " + location); + logger.info("Adding new policy to PDPGroup - " + newPolicy.getId() + ", Location - " + location); } catch (Exception e) { logger.debug(e); - PolicyLogger.error( - "PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + PolicyLogger + .error("PolicyDBDao: Exception occurred while creating the StdPDPPolicy newPolicy object " + e.getMessage()); } } @@ -450,15 +437,13 @@ public class PolicyDBDao { } } - logger.info( - "PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); + logger.info("PolicyDBDao: Adding new policy set to group to keep filesystem and DB in sync"); pdpGroup.setPolicies(newPolicySet); return pdpGroup; } - public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) - throws PolicyDBException { + public String removeExtensionAndVersionFromPolicyName(String originalPolicyName) throws PolicyDBException { return getPolicyNameAndVersionFromPolicyFileName(originalPolicyName)[0]; } @@ -468,8 +453,7 @@ public class PolicyDBDao { * @param originalPolicyName: a policy file name ex: Config_policy.2.xml * @return An array [0]: The policy name, [1]: the policy version, as a string */ - public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) - throws PolicyDBException { + public String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException { String policyName = originalPolicyName; String[] nameAndVersion = new String[2]; try { @@ -513,8 +497,7 @@ public class PolicyDBDao { deleteAllGroupTables(); auditGroups(papEngine2); } catch (Exception e) { - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, - "auditLocalDatabase() error"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "auditLocalDatabase() error"); logger.error("Exception Occured" + e); } } @@ -534,8 +517,7 @@ public class PolicyDBDao { if (groupQueryList != null && !groupQueryList.isEmpty()) { GroupEntity dbgroup = (GroupEntity) groupQueryList.get(0); updatedGroup = synchronizeGroupPoliciesInFileSystem(group, dbgroup); - logger.info( - "Group was updated during file system audit: " + updatedGroup.toString()); + logger.info("Group was updated during file system audit: " + updatedGroup.toString()); } } catch (PAPException | PolicyDBException e) { logger.error(e); @@ -543,8 +525,7 @@ public class PolicyDBDao { logger.error(e); PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Caught Exception trying to check if group exists groupQuery.getResultList()"); - throw new PersistenceException( - "Query failed trying to check if group " + group.getId() + " exists"); + throw new PersistenceException("Query failed trying to check if group " + group.getId() + " exists"); } session.getTransaction().commit(); @@ -571,8 +552,7 @@ public class PolicyDBDao { final Criteria configDataQuery = session.createCriteria(cl.getName()); @SuppressWarnings("unchecked") final List<T> configDataResult = configDataQuery.list(); - Path webappsPath = Paths - .get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type); + Path webappsPath = Paths.get(XACMLProperties.getProperty(XACMLRestProperties.PROP_PAP_WEBAPPS), type); for (final T configData : configDataResult) { String configName = null; @@ -588,8 +568,7 @@ public class PolicyDBDao { } else { configName = ((ActionBodyEntity) configData).getActionBodyName(); configBody = (((ActionBodyEntity) configData).getActionBody() != null) - ? ((ActionBodyEntity) configData).getActionBody() - .getBytes(StandardCharsets.UTF_8) + ? ((ActionBodyEntity) configData).getActionBody().getBytes(StandardCharsets.UTF_8) : "".getBytes(); } Path filePath = Paths.get(webappsPath.toString(), configName); @@ -662,15 +641,13 @@ public class PolicyDBDao { for (PDPPolicy policy : policies) { try { - String[] stringArray = - getNameScopeAndVersionFromPdpPolicy(policy.getId()); + String[] stringArray = getNameScopeAndVersionFromPdpPolicy(policy.getId()); if (stringArray == null) { throw new IllegalArgumentException( "Invalid input - policyID must contain name, scope and version"); } List<PolicyEntity> policyEntityList; - Query getPolicyEntitiesQuery = - session.getNamedQuery("PolicyEntity.findByNameAndScope"); + Query getPolicyEntitiesQuery = session.getNamedQuery("PolicyEntity.findByNameAndScope"); getPolicyEntitiesQuery.setParameter("name", stringArray[0]); getPolicyEntitiesQuery.setParameter(SCOPE, stringArray[1]); @@ -694,8 +671,7 @@ public class PolicyDBDao { } } catch (Exception e) { session.getTransaction().rollback(); - PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, - "Exception auditGroups outer catch"); + PolicyLogger.error(MessageCodes.EXCEPTION_ERROR, e, POLICYDBDAO_VAR, "Exception auditGroups outer catch"); session.close(); return; } @@ -717,9 +693,8 @@ public class PolicyDBDao { // config type selection for saving. public String getConfigFile(String inputFilename, String configType) { String filename = inputFilename; - logger.debug( - "getConfigFile(String filename, String scope, String configType) as getConfigFile(" - + filename + ", " + configType + ") called"); + logger.debug("getConfigFile(String filename, String scope, String configType) as getConfigFile(" + filename + + ", " + configType + ") called"); filename = FilenameUtils.removeExtension(filename); String id = configType; @@ -812,7 +787,6 @@ public class PolicyDBDao { return papEngine; } - public static boolean isJunit() { return isJunit; } @@ -830,8 +804,7 @@ public class PolicyDBDao { return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy); } - String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) - throws PolicyDBException { + String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException { return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java index dbb2fa830..250029a89 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTransaction.java @@ -21,8 +21,11 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; + import java.util.List; + import javax.persistence.PersistenceException; + import org.onap.policy.rest.dao.PolicyDBException; import org.onap.policy.rest.jpa.GroupEntity; import org.onap.policy.rest.jpa.PdpEntity; @@ -70,7 +73,6 @@ public interface PolicyDBDaoTransaction { */ public void close(); - /** * Create a new PDP group in the database * @@ -162,7 +164,6 @@ public interface PolicyDBDaoTransaction { public StdPDPGroup addPolicyToGroup(String group, String policyID, String requestType, String username) throws PolicyDBException; - /** * Delete an existing PDP groupPolicyDBException * diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java index f63649ddc..347db92d7 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/PolicyDbDaoTransactionInstance.java @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -36,14 +37,17 @@ import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; + import javax.persistence.PersistenceException; import javax.persistence.RollbackException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathFactory; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicySetType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; + import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.hibernate.Query; @@ -71,7 +75,6 @@ import org.springframework.stereotype.Component; import org.w3c.dom.Document; import org.xml.sax.InputSource; - @Component public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { @@ -88,7 +91,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private static final String PDP_NOTIFICATION = "pdp"; private static final String GROUP_NOTIFICATION = "group"; - private static final String DECISIONMS_MODEL = "MicroService_Model"; private static boolean isJunit = false; Session session; @@ -115,7 +117,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { private static SessionFactory sessionfactory; - /** * Instantiates a new policy DB dao transaction instance. * @@ -629,7 +630,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { } } - public PolicyEntity getPolicy(int policyId) { return getPolicy(policyId, null, null); } @@ -835,7 +835,6 @@ public class PolicyDbDaoTransactionInstance implements PolicyDBDaoTransaction { return configDataString; } - @Override public void close() { synchronized (emLock) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java index 7a0f708d8..6ef7a8f18 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/components/SafePolicyBuilder.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import java.util.List; @@ -31,8 +32,8 @@ import org.yaml.snakeyaml.constructor.Constructor; public class SafePolicyBuilder { - private SafePolicyBuilder(){ - //Private Constructor. + private SafePolicyBuilder() { + // Private Constructor. } public static ControlLoopGuard loadYamlGuard(String specification) { @@ -45,40 +46,42 @@ public class SafePolicyBuilder { return (ControlLoopGuard) obj; } - public static String generateXacmlGuard(String xacmlFileContent,Map<String, String> generateMap, List<String> blacklist, List<String> targets) { - //Setup default values and Targets. - StringBuilder targetRegex= new StringBuilder(".*|"); - if(targets!=null && !targets.isEmpty()){ + public static String generateXacmlGuard(String xacmlFileContent, Map<String, String> generateMap, + List<String> blacklist, List<String> targets) { + // Setup default values and Targets. + StringBuilder targetRegex = new StringBuilder(".*|"); + if (targets != null && !targets.isEmpty()) { targetRegex = new StringBuilder(); - for(String t : targets){ + for (String t : targets) { targetRegex.append(t + "|"); } } - if(generateMap.get("clname")==null|| generateMap.get("clname").isEmpty()){ - generateMap.put("clname",".*"); + if (generateMap.get("clname") == null || generateMap.get("clname").isEmpty()) { + generateMap.put("clname", ".*"); } - generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length()-1)); + generateMap.put("targets", targetRegex.toString().substring(0, targetRegex.length() - 1)); // Replace values. - for(Map.Entry<String,String> map: generateMap.entrySet()){ - Pattern p = Pattern.compile("\\$\\{" +map.getKey() +"\\}"); + for (Map.Entry<String, String> map : generateMap.entrySet()) { + Pattern p = Pattern.compile("\\$\\{" + map.getKey() + "\\}"); Matcher m = p.matcher(xacmlFileContent); String finalInput = map.getValue(); - if(finalInput.contains("$")){ + if (finalInput.contains("$")) { finalInput = finalInput.replace("$", "\\$"); } - xacmlFileContent=m.replaceAll(finalInput); + xacmlFileContent = m.replaceAll(finalInput); } - if(blacklist!=null && !blacklist.isEmpty()){ + if (blacklist != null && !blacklist.isEmpty()) { StringBuilder rule = new StringBuilder(); - for(String blackListName : blacklist){ - if(blackListName.contains("$")){ + for (String blackListName : blacklist) { + if (blackListName.contains("$")) { blackListName = blackListName.replace("$", "\\$"); } - rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">"+blackListName+"</AttributeValue>"); + rule.append("<AttributeValue DataType=\"http://www.w3.org/2001/XMLSchema#string\">" + blackListName + + "</AttributeValue>"); } Pattern p = Pattern.compile("\\$\\{blackListElement\\}"); Matcher m = p.matcher(xacmlFileContent); - xacmlFileContent=m.replaceAll(rule.toString()); + xacmlFileContent = m.replaceAll(rule.toString()); } PolicyLogger.info("Generated XACML from the YAML Spec: \n" + xacmlFileContent); return xacmlFileContent; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java index 8e620408b..f576bffe8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -20,6 +20,10 @@ package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; @@ -38,10 +42,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - @Controller public class ActionPolicyDictionaryController { @@ -51,36 +51,43 @@ public class ActionPolicyDictionaryController { private static String actionDatas = "actionPolicyDictionaryDatas"; @Autowired - public ActionPolicyDictionaryController(CommonClassDao commonClassDao){ + public ActionPolicyDictionaryController(CommonClassDao commonClassDao) { ActionPolicyDictionaryController.commonClassDao = commonClassDao; } - public void setCommonClassDao(CommonClassDao commonClassDao){ + public void setCommonClassDao(CommonClassDao commonClassDao) { ActionPolicyDictionaryController.commonClassDao = commonClassDao; } - public ActionPolicyDictionaryController(){ + public ActionPolicyDictionaryController() { super(); } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value={"/get_ActionPolicyDictDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionEntitybyName(HttpServletResponse response){ + @RequestMapping( + value = {"/get_ActionPolicyDictDataByName"}, + method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getActionEntitybyName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, actionDatas, attributeName, ActionPolicyDict.class); } - @RequestMapping(value={"/get_ActionPolicyDictData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getActionPolicyDictionaryEntityData(HttpServletResponse response){ + @RequestMapping( + value = {"/get_ActionPolicyDictData"}, + method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getActionPolicyDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, actionDatas, ActionPolicyDict.class); } - @RequestMapping(value={"/action_dictionary/save_ActionDict"}, method={RequestMethod.POST}) - public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/action_dictionary/save_ActionDict"}, method = {RequestMethod.POST}) + public ModelAndView saveActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -90,63 +97,68 @@ public class ActionPolicyDictionaryController { ActionPolicyDict actionPolicyDict = null; ActionAdapter adapter = null; String userId = null; - if(fromAPI){ + if (fromAPI) { actionPolicyDict = mapper.readValue(root.get("dictionaryFields").toString(), ActionPolicyDict.class); adapter = mapper.readValue(root.get("dictionaryFields").toString(), ActionAdapter.class); userId = "API"; - }else{ - actionPolicyDict = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class); + } else { + actionPolicyDict = + mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionPolicyDict.class); adapter = mapper.readValue(root.get("actionPolicyDictionaryData").toString(), ActionAdapter.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), attributeName, ActionPolicyDict.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(actionPolicyDict.getAttributeName(), + attributeName, ActionPolicyDict.class); boolean duplicateflag = false; - if(!duplicateData.isEmpty()){ + if (!duplicateData.isEmpty()) { ActionPolicyDict data = (ActionPolicyDict) duplicateData.get(0); - if(request.getParameter(operation) != null && "update".equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { actionPolicyDict.setId(data.getId()); - }else if((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != actionPolicyDict.getId()))){ + } else if ((request.getParameter(operation) != null + && !"update".equals(request.getParameter(operation))) + || (request.getParameter(operation) == null && (data.getId() != actionPolicyDict.getId()))) { duplicateflag = true; } } actionPolicyDict.setHeader(utils.appendKeyValue(adapter.getHeaders(), ":", "=")); String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { actionPolicyDict.setUserModifiedBy(userInfo); - if(actionPolicyDict.getId() == 0){ + if (actionPolicyDict.getId() == 0) { actionPolicyDict.setUserCreatedBy(userInfo); commonClassDao.save(actionPolicyDict); - }else{ + } else { actionPolicyDict.setModifiedDate(new Date()); commonClassDao.update(actionPolicyDict); } responseString = mapper.writeValueAsString(commonClassDao.getData(ActionPolicyDict.class)); - }else{ + } else { responseString = "Duplicate"; } - if(fromAPI){ + if (fromAPI) { return utils.getResultForApi(responseString); - }else{ + } else { utils.setResponseData(response, actionDatas, responseString); } - }catch(Exception e){ + } catch (Exception e) { utils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/action_dictionary/remove_actionPolicyDict"}, method={RequestMethod.POST}) - public void removeActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/action_dictionary/remove_actionPolicyDict"}, method = {RequestMethod.POST}) + public void removeActionPolicyDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, actionDatas, ActionPolicyDict.class); } } -class ActionAdapter{ + +class ActionAdapter { private List<Object> headers; public List<Object> getHeaders() { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java index d6ebed2b8..a669d82a0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryController.java @@ -23,13 +23,16 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.io.IOUtils; import org.onap.policy.api.PEDependency; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -51,7 +54,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; - @Controller public class BRMSDictionaryController { @@ -91,14 +93,18 @@ public class BRMSDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_BRMSParamDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSParamDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSParamDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, brmsParamDatas, ruleName, BRMSParamTemplate.class); } - @RequestMapping(value = {"/get_BRMSParamData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSParamData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSParamDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -109,14 +115,13 @@ public class BRMSDictionaryController { public static void setRuleData(HttpServletRequest request) throws IOException { StringWriter writer = new StringWriter(); IOUtils.copy(request.getInputStream(), writer, StandardCharsets.UTF_8); - String cleanStreamBoundary = - writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); + String cleanStreamBoundary = writer.toString().replaceFirst("------(.*)(?s).*octet-stream", ""); rule = cleanStreamBoundary.substring(0, cleanStreamBoundary.lastIndexOf("end") + 4); } @RequestMapping(value = {"/brms_dictionary/save_BRMSParam"}, method = {RequestMethod.POST}) - public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -127,23 +132,22 @@ public class BRMSDictionaryController { BRMSParamTemplate bRMSParamTemplateData; String userId = null; if (fromAPI) { - bRMSParamTemplateData = mapper.readValue(root.get(dictionaryFields).toString(), - BRMSParamTemplate.class); + bRMSParamTemplateData = + mapper.readValue(root.get(dictionaryFields).toString(), BRMSParamTemplate.class); userId = "API"; } else { - bRMSParamTemplateData = mapper.readValue( - root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); + bRMSParamTemplateData = + mapper.readValue(root.get("brmsParamDictionaryData").toString(), BRMSParamTemplate.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - bRMSParamTemplateData.getRuleName(), ruleName, BRMSParamTemplate.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(bRMSParamTemplateData.getRuleName(), + ruleName, BRMSParamTemplate.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { BRMSParamTemplate data = (BRMSParamTemplate) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { bRMSParamTemplateData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) @@ -164,8 +168,7 @@ public class BRMSDictionaryController { } else { commonClassDao.update(bRMSParamTemplateData); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class)); } else { responseString = duplicateResponseString; } @@ -192,30 +195,32 @@ public class BRMSDictionaryController { } @RequestMapping(value = {"/brms_dictionary/remove_brmsParam"}, method = {RequestMethod.POST}) - public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeBRMSParamDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, brmsParamDatas, BRMSParamTemplate.class); } - @RequestMapping(value = {"/get_BRMSDependencyDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSDependencyDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSDependencyDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, brmsDependencyDatas, dependencyName, BRMSDependency.class); } - @RequestMapping(value = {"/get_BRMSDependencyData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSDependencyData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSDependencyDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, brmsDependencyDatas, BRMSDependency.class); } - @RequestMapping(value = {"/brms_dictionary/save_BRMSDependencyData"}, - method = {RequestMethod.POST}) - public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/save_BRMSDependencyData"}, method = {RequestMethod.POST}) + public ModelAndView saveBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { LOGGER.debug("DictionaryController: saveBRMSDependencyDictionary() is called"); @@ -227,43 +232,38 @@ public class BRMSDictionaryController { BRMSDependency brmsDependency; String userId = null; if (fromAPI) { - brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), - BRMSDependency.class); + brmsDependency = mapper.readValue(root.get(dictionaryFields).toString(), BRMSDependency.class); userId = "API"; } else { - brmsDependency = mapper.readValue( - root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); + brmsDependency = + mapper.readValue(root.get("brmsDependencyDictionaryData").toString(), BRMSDependency.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - brmsDependency.getDependencyName(), dependencyName, BRMSDependency.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsDependency.getDependencyName(), + dependencyName, BRMSDependency.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { BRMSDependency data = (BRMSDependency) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { brmsDependency.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != brmsDependency.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != brmsDependency.getId()))) { duplicateflag = true; } } LOGGER.audit("the userId from the onap portal is: " + userId); String responseString = null; - if (brmsDependency.getDependency() != null - && !("").equals(brmsDependency.getDependency().trim())) { + if (brmsDependency.getDependency() != null && !("").equals(brmsDependency.getDependency().trim())) { PEDependency dependency = null; try { - dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), - PEDependency.class); + dependency = PolicyUtils.jsonStringToObject(brmsDependency.getDependency(), PEDependency.class); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID - + "wrong data given for BRMS PEDependency Dictionary : " - + brmsDependency.getDependency(), e); + + "wrong data given for BRMS PEDependency Dictionary : " + brmsDependency.getDependency(), + e); } if (dependency == null) { responseString = errorMessage; @@ -277,8 +277,7 @@ public class BRMSDictionaryController { brmsDependency.setModifiedDate(new Date()); commonClassDao.update(brmsDependency); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(BRMSDependency.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class)); } else { responseString = duplicateResponseString; } @@ -302,33 +301,34 @@ public class BRMSDictionaryController { return null; } - @RequestMapping(value = {"/brms_dictionary/remove_brmsDependency"}, - method = {RequestMethod.POST}) - public void removeBRMSDependencyDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/remove_brmsDependency"}, method = {RequestMethod.POST}) + public void removeBRMSDependencyDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, brmsDependencyDatas, BRMSDependency.class); } - - @RequestMapping(value = {"/get_BRMSControllerDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSControllerDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSControllerDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, brmsControllerDatas, controllerName, BRMSController.class); } - @RequestMapping(value = {"/get_BRMSControllerData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_BRMSControllerData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getBRMSControllerDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, brmsControllerDatas, BRMSController.class); } - @RequestMapping(value = {"/brms_dictionary/save_BRMSControllerData"}, - method = {RequestMethod.POST}) - public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/save_BRMSControllerData"}, method = {RequestMethod.POST}) + public ModelAndView saveBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { LOGGER.debug("DictionaryController: saveBRMSControllerDictionary() is called"); @@ -339,42 +339,36 @@ public class BRMSDictionaryController { BRMSController brmsController; String userId = null; if (fromAPI) { - brmsController = mapper.readValue(root.get(dictionaryFields).toString(), - BRMSController.class); + brmsController = mapper.readValue(root.get(dictionaryFields).toString(), BRMSController.class); userId = "API"; } else { - brmsController = mapper.readValue( - root.get("brmsControllerDictionaryData").toString(), BRMSController.class); + brmsController = + mapper.readValue(root.get("brmsControllerDictionaryData").toString(), BRMSController.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - brmsController.getControllerName(), controllerName, BRMSController.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(brmsController.getControllerName(), + controllerName, BRMSController.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { BRMSController data = (BRMSController) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { brmsController.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != brmsController.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != brmsController.getId()))) { duplicateflag = true; } } String responseString = null; - if (brmsController.getController() != null - && !("").equals(brmsController.getController().trim())) { + if (brmsController.getController() != null && !("").equals(brmsController.getController().trim())) { PEDependency dependency = null; try { - dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), - PEDependency.class); + dependency = PolicyUtils.jsonStringToObject(brmsController.getController(), PEDependency.class); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_SCHEMA_INVALID - + "wrong data given for BRMS Controller Dictionary : " - + brmsController.getController(), e); + + "wrong data given for BRMS Controller Dictionary : " + brmsController.getController(), e); } if (dependency == null) { responseString = errorMessage; @@ -388,8 +382,7 @@ public class BRMSDictionaryController { brmsController.setModifiedDate(new Date()); commonClassDao.update(brmsController); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class)); } else { responseString = duplicateResponseString; } @@ -412,10 +405,9 @@ public class BRMSDictionaryController { return null; } - @RequestMapping(value = {"/brms_dictionary/remove_brmsController"}, - method = {RequestMethod.POST}) - public void removeBRMSControllerDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/brms_dictionary/remove_brmsController"}, method = {RequestMethod.POST}) + public void removeBRMSControllerDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, brmsControllerDatas, BRMSController.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java index 2aec0cc0d..0b94b40bc 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.adapters.GridData; import org.onap.policy.pap.xacml.rest.daoimpl.CommonClassDaoImpl; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; @@ -89,85 +92,108 @@ public class ClosedLoopDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_VSCLActionDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VSCLActionDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVSCLActionDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, vsclActionDatas, vsclaction, VSCLAction.class); } - - @RequestMapping(value = {"/get_VSCLActionData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VSCLActionData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVSCLActionDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, vsclActionDatas, VSCLAction.class); } - @RequestMapping(value = {"/get_VNFTypeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VNFTypeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVNFTypeDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, vnfTypeDatas, vnftype, VNFType.class); } - @RequestMapping(value = {"/get_VNFTypeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VNFTypeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVNFTypeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, vnfTypeDatas, VNFType.class); } - @RequestMapping(value = {"/get_PEPOptionsDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PEPOptionsDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPEPOptionsDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, pepOptionDatas, pepName, PEPOptions.class); } - @RequestMapping(value = {"/get_PEPOptionsData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PEPOptionsData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPEPOptionsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, pepOptionDatas, PEPOptions.class); } - @RequestMapping(value = {"/get_VarbindDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VarbindDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVarbindDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, varbindDatas, varbindName, VarbindDictionary.class); } - @RequestMapping(value = {"/get_VarbindDictionaryData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_VarbindDictionaryData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getVarbindDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, varbindDatas, VarbindDictionary.class); } - @RequestMapping(value = {"/get_ClosedLoopServicesDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ClosedLoopServicesDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopServiceDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, closedLoopDatas, serviceName, ClosedLoopD2Services.class); } - @RequestMapping(value = {"/get_ClosedLoopServicesData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ClosedLoopServicesData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopServiceDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, closedLoopDatas, ClosedLoopD2Services.class); } - @RequestMapping(value = {"/get_ClosedLoopSiteDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ClosedLoopSiteDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopSiteDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, closedLoopSiteDatas, siteName, ClosedLoopSite.class); } - @RequestMapping(value = {"/get_ClosedLoopSiteData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ClosedLoopSiteData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getClosedLoopSiteDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -175,8 +201,7 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/save_vsclAction"}, method = {RequestMethod.POST}) - public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -186,28 +211,24 @@ public class ClosedLoopDictionaryController { VSCLAction vSCLAction; String userId = null; if (fromAPI) { - vSCLAction = - mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class); + vSCLAction = mapper.readValue(root.get(dictionaryFields).toString(), VSCLAction.class); userId = "API"; } else { - vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), - VSCLAction.class); + vSCLAction = mapper.readValue(root.get("vsclActionDictionaryData").toString(), VSCLAction.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(vSCLAction.getVsclaction(), vsclaction, VSCLAction.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { VSCLAction data = (VSCLAction) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { vSCLAction.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != vSCLAction.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != vSCLAction.getId()))) { duplicateflag = true; } } @@ -221,8 +242,7 @@ public class ClosedLoopDictionaryController { vSCLAction.setModifiedDate(new Date()); commonClassDao.update(vSCLAction); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class)); } else { responseString = duplicateResponseString; } @@ -239,15 +259,13 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_VsclAction"}, method = {RequestMethod.POST}) - public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeVSCLAction(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, vsclActionDatas, OnapName.class); } @RequestMapping(value = {"/cl_dictionary/save_vnfType"}, method = {RequestMethod.POST}) - public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -260,24 +278,21 @@ public class ClosedLoopDictionaryController { vNFType = mapper.readValue(root.get(dictionaryFields).toString(), VNFType.class); userId = "API"; } else { - vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), - VNFType.class); + vNFType = mapper.readValue(root.get("vnfTypeDictionaryData").toString(), VNFType.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), - vnftype, VNFType.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(vNFType.getVnftype(), vnftype, VNFType.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { VNFType data = (VNFType) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { vNFType.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != vNFType.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != vNFType.getId()))) { duplicateflag = true; } } @@ -308,15 +323,13 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_vnfType"}, method = {RequestMethod.POST}) - public void removeVnfType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeVnfType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, vnfTypeDatas, VNFType.class); } @RequestMapping(value = {"/cl_dictionary/save_pepOptions"}, method = {RequestMethod.POST}) - public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView savePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -327,15 +340,12 @@ public class ClosedLoopDictionaryController { GridData gridData; String userId = null; if (fromAPI) { - pEPOptions = - mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class); + pEPOptions = mapper.readValue(root.get(dictionaryFields).toString(), PEPOptions.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); userId = "API"; } else { - pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), - PEPOptions.class); - gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), - GridData.class); + pEPOptions = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), PEPOptions.class); + gridData = mapper.readValue(root.get("pepOptionsDictionaryData").toString(), GridData.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); @@ -344,18 +354,16 @@ public class ClosedLoopDictionaryController { pEPOptions.setActions(utils.appendKeyValue(gridData.getAttributes(), ":#@", "=#@")); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), - pepName, PEPOptions.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(pEPOptions.getPepName(), pepName, PEPOptions.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PEPOptions data = (PEPOptions) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { pEPOptions.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != pEPOptions.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != pEPOptions.getId()))) { duplicateflag = true; } } @@ -369,8 +377,7 @@ public class ClosedLoopDictionaryController { pEPOptions.setModifiedDate(new Date()); commonClassDao.update(pEPOptions); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class)); } else { responseString = duplicateResponseString; } @@ -387,15 +394,13 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_pepOptions"}, method = {RequestMethod.POST}) - public void removePEPOptions(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removePEPOptions(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, pepOptionDatas, VNFType.class); } @RequestMapping(value = {"/cl_dictionary/save_service"}, method = {RequestMethod.POST}) - public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -405,29 +410,25 @@ public class ClosedLoopDictionaryController { ClosedLoopD2Services serviceData; String userId = null; if (fromAPI) { - serviceData = mapper.readValue(root.get(dictionaryFields).toString(), - ClosedLoopD2Services.class); + serviceData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopD2Services.class); userId = "API"; } else { - serviceData = - mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), - ClosedLoopD2Services.class); + serviceData = mapper.readValue(root.get("closedLoopServiceDictionaryData").toString(), + ClosedLoopD2Services.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - serviceData.getServiceName(), serviceName, ClosedLoopD2Services.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(serviceData.getServiceName(), serviceName, + ClosedLoopD2Services.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ClosedLoopD2Services data = (ClosedLoopD2Services) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { serviceData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != serviceData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != serviceData.getId()))) { duplicateflag = true; } } @@ -441,8 +442,7 @@ public class ClosedLoopDictionaryController { serviceData.setModifiedDate(new Date()); commonClassDao.update(serviceData); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class)); } else { responseString = duplicateResponseString; } @@ -458,15 +458,13 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_Service"}, method = {RequestMethod.POST}) - public void removeServiceType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeServiceType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, closedLoopDatas, VNFType.class); } @RequestMapping(value = {"/cl_dictionary/save_siteName"}, method = {RequestMethod.POST}) - public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -476,28 +474,24 @@ public class ClosedLoopDictionaryController { ClosedLoopSite siteData; String userId = null; if (fromAPI) { - siteData = mapper.readValue(root.get(dictionaryFields).toString(), - ClosedLoopSite.class); + siteData = mapper.readValue(root.get(dictionaryFields).toString(), ClosedLoopSite.class); userId = "API"; } else { - siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), - ClosedLoopSite.class); + siteData = mapper.readValue(root.get("closedLoopSiteDictionaryData").toString(), ClosedLoopSite.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(siteData.getSiteName(), - siteName, ClosedLoopSite.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(siteData.getSiteName(), siteName, ClosedLoopSite.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ClosedLoopSite data = (ClosedLoopSite) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { siteData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != siteData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != siteData.getId()))) { duplicateflag = true; } } @@ -511,8 +505,7 @@ public class ClosedLoopDictionaryController { siteData.setModifiedDate(new Date()); commonClassDao.update(siteData); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class)); } else { responseString = duplicateResponseString; } @@ -528,15 +521,13 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_site"}, method = {RequestMethod.POST}) - public void removeSiteType(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeSiteType(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, closedLoopSiteDatas, VNFType.class); } @RequestMapping(value = {"/cl_dictionary/save_varbind"}, method = {RequestMethod.POST}) - public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public ModelAndView saveVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -546,28 +537,25 @@ public class ClosedLoopDictionaryController { VarbindDictionary varbindDictionary; String userId = null; if (fromAPI) { - varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), - VarbindDictionary.class); + varbindDictionary = mapper.readValue(root.get(dictionaryFields).toString(), VarbindDictionary.class); userId = "API"; } else { - varbindDictionary = mapper.readValue(root.get("varbindDictionaryData").toString(), - VarbindDictionary.class); + varbindDictionary = + mapper.readValue(root.get("varbindDictionaryData").toString(), VarbindDictionary.class); userId = root.get(userid).textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - varbindDictionary.getVarbindName(), varbindName, VarbindDictionary.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(varbindDictionary.getVarbindName(), + varbindName, VarbindDictionary.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { VarbindDictionary data = (VarbindDictionary) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { varbindDictionary.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != varbindDictionary.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != varbindDictionary.getId()))) { duplicateflag = true; } } @@ -582,8 +570,7 @@ public class ClosedLoopDictionaryController { varbindDictionary.setModifiedDate(new Date()); commonClassDao.update(varbindDictionary); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class)); } else { responseString = duplicateResponseString; } @@ -599,8 +586,7 @@ public class ClosedLoopDictionaryController { } @RequestMapping(value = {"/cl_dictionary/remove_varbindDict"}, method = {RequestMethod.POST}) - public void removeVarbind(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeVarbind(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, varbindDatas, VNFType.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java index c89d21e91..4b6492baa 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryController.java @@ -23,12 +23,15 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.DecisionSettings; @@ -66,16 +69,18 @@ public class DecisionPolicyDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_SettingsDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SettingsDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) - public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, - HttpServletResponse response) { + public void getSettingsDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, settingDatas, xacmlId, DecisionSettings.class); } - - @RequestMapping(value = {"/get_SettingsDictionaryData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SettingsDictionaryData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSettingsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -83,8 +88,8 @@ public class DecisionPolicyDictionaryController { } @RequestMapping(value = {"/decision_dictionary/save_Settings"}, method = {RequestMethod.POST}) - public ModelAndView saveSettingsDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveSettingsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -95,27 +100,24 @@ public class DecisionPolicyDictionaryController { String userId = null; if (fromAPI) { - decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), - DecisionSettings.class); + decisionSettings = mapper.readValue(root.get(dictionaryFields).toString(), DecisionSettings.class); userId = "API"; } else { - decisionSettings = mapper.readValue(root.get("settingsDictionaryData").toString(), - DecisionSettings.class); + decisionSettings = + mapper.readValue(root.get("settingsDictionaryData").toString(), DecisionSettings.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(decisionSettings.getXacmlId(), xacmlId, DecisionSettings.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { DecisionSettings data = (DecisionSettings) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { decisionSettings.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != decisionSettings.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != decisionSettings.getId()))) { duplicateflag = true; } } @@ -133,8 +135,7 @@ public class DecisionPolicyDictionaryController { decisionSettings.setModifiedDate(new Date()); commonClassDao.update(decisionSettings); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class)); } else { responseString = duplicateResponseString; } @@ -150,21 +151,23 @@ public class DecisionPolicyDictionaryController { } @RequestMapping(value = {"/settings_dictionary/remove_settings"}, method = {RequestMethod.POST}) - public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeSettingsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, settingDatas, DecisionSettings.class); } - @RequestMapping(value = {"/get_RainyDayDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_RainyDayDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) - public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, - HttpServletResponse response) { + public void getRainyDayDictionaryByNameEntityData(HttpServletRequest request, HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, rainDayDatas, bbID, RainyDayTreatments.class); } - @RequestMapping(value = {"/get_RainyDayDictionaryData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_RainyDayDictionaryData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getRainyDayDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -172,8 +175,8 @@ public class DecisionPolicyDictionaryController { } @RequestMapping(value = {"/decision_dictionary/save_RainyDay"}, method = {RequestMethod.POST}) - public ModelAndView saveRainyDayDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -183,32 +186,26 @@ public class DecisionPolicyDictionaryController { RainyDayTreatments decisionRainyDay; TreatmentValues treatmentsData = null; if (fromAPI) { - decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(), - RainyDayTreatments.class); - treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(), - TreatmentValues.class); + decisionRainyDay = mapper.readValue(root.get(dictionaryFields).toString(), RainyDayTreatments.class); + treatmentsData = mapper.readValue(root.get(dictionaryFields).toString(), TreatmentValues.class); } else { - decisionRainyDay = mapper.readValue(root.get("rainyDayDictionaryData").toString(), - RainyDayTreatments.class); - treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(), - TreatmentValues.class); + decisionRainyDay = + mapper.readValue(root.get("rainyDayDictionaryData").toString(), RainyDayTreatments.class); + treatmentsData = mapper.readValue(root.get("rainyDayDictionaryData").toString(), TreatmentValues.class); } - decisionRainyDay.setTreatments( - utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ",")); + decisionRainyDay.setTreatments(utils.appendKey(treatmentsData.getUserDataTypeValues(), "treatment", ",")); List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - decisionRainyDay.getBbid() + ":" + decisionRainyDay.getWorkstep(), - "bbid:workstep", RainyDayTreatments.class); + decisionRainyDay.getBbid() + ":" + decisionRainyDay.getWorkstep(), "bbid:workstep", + RainyDayTreatments.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { RainyDayTreatments data = (RainyDayTreatments) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { decisionRainyDay.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != decisionRainyDay.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != decisionRainyDay.getId()))) { duplicateflag = true; } } @@ -219,8 +216,7 @@ public class DecisionPolicyDictionaryController { } else { commonClassDao.update(decisionRainyDay); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class)); } else { responseString = duplicateResponseString; } @@ -236,8 +232,7 @@ public class DecisionPolicyDictionaryController { } @RequestMapping(value = {"/decision_dictionary/remove_rainyDay"}, method = {RequestMethod.POST}) - public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeRainyDayDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, rainDayDatas, RainyDayTreatments.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java index 51c8a1d91..1645b0af9 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.adapters.GridData; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; @@ -65,24 +68,27 @@ public class DescriptiveDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_DescriptiveScopeByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_DescriptiveScopeByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDescriptiveDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, descriptiveDatas, dScopeName, DescriptiveScope.class); } - @RequestMapping(value = {"/get_DescriptiveScope"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_DescriptiveScope"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDescriptiveDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, descriptiveDatas, DescriptiveScope.class); } - @RequestMapping(value = {"/descriptive_dictionary/save_descriptive"}, - method = {RequestMethod.POST}) - public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/descriptive_dictionary/save_descriptive"}, method = {RequestMethod.POST}) + public ModelAndView saveDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -93,32 +99,27 @@ public class DescriptiveDictionaryController { GridData data; String userId = null; if (fromAPI) { - descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), - DescriptiveScope.class); + descriptiveScope = mapper.readValue(root.get("dictionaryFields").toString(), DescriptiveScope.class); data = mapper.readValue(root.get("dictionaryFields").toString(), GridData.class); userId = "API"; } else { descriptiveScope = - mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), - DescriptiveScope.class); - data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), - GridData.class); + mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), DescriptiveScope.class); + data = mapper.readValue(root.get("descriptiveScopeDictionaryData").toString(), GridData.class); userId = root.get("userid").textValue(); } descriptiveScope.setSearch(utils.appendKeyValue(data.getAttributes(), "AND", ":")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - descriptiveScope.getScopeName(), dScopeName, DescriptiveScope.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(descriptiveScope.getScopeName(), dScopeName, + DescriptiveScope.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { DescriptiveScope data1 = (DescriptiveScope) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { descriptiveScope.setId(data1.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data1.getId() != descriptiveScope.getId()))) { + || (request.getParameter(operation) == null && (data1.getId() != descriptiveScope.getId()))) { duplicateflag = true; } } @@ -132,8 +133,7 @@ public class DescriptiveDictionaryController { descriptiveScope.setModifiedDate(new Date()); commonClassDao.update(descriptiveScope); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class)); } else { responseString = "Duplicate"; } @@ -148,10 +148,9 @@ public class DescriptiveDictionaryController { return null; } - @RequestMapping(value = {"/descriptive_dictionary/remove_descriptiveScope"}, - method = {RequestMethod.POST}) - public void removeDescriptiveDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/descriptive_dictionary/remove_descriptiveScope"}, method = {RequestMethod.POST}) + public void removeDescriptiveDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, descriptiveDatas, DescriptiveScope.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java index 94275e7c1..5de2dfbc2 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; @@ -69,7 +72,9 @@ public class DictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_AttributeDatabyAttributeName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_AttributeDatabyAttributeName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getAttributeDictionaryEntityDatabyAttributeName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -77,7 +82,9 @@ public class DictionaryController { } // Attribute Dictionary - @RequestMapping(value = "/get_AttributeData", method = RequestMethod.GET, + @RequestMapping( + value = "/get_AttributeData", + method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public void getAttributeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -85,8 +92,8 @@ public class DictionaryController { } @RequestMapping(value = {"/attribute_dictionary/save_attribute"}, method = {RequestMethod.POST}) - public ModelAndView saveAttributeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveAttributeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -97,38 +104,33 @@ public class DictionaryController { AttributeValues attributeValueData = null; String userId = null; if (fromAPI) { - attributeData = - mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class); - attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(), - AttributeValues.class); + attributeData = mapper.readValue(root.get(dictionaryFields).toString(), Attribute.class); + attributeValueData = mapper.readValue(root.get(dictionaryFields).toString(), AttributeValues.class); userId = "API"; } else { - attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(), - Attribute.class); - attributeValueData = mapper.readValue( - root.get("attributeDictionaryData").toString(), AttributeValues.class); + attributeData = mapper.readValue(root.get("attributeDictionaryData").toString(), Attribute.class); + attributeValueData = + mapper.readValue(root.get("attributeDictionaryData").toString(), AttributeValues.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(attributeData.getXacmlId(), xacmlId, Attribute.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { Attribute data = (Attribute) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { attributeData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != attributeData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != attributeData.getId()))) { duplicateflag = true; } } if (attributeValueData.getUserDataTypeValues() != null && !attributeValueData.getUserDataTypeValues().isEmpty()) { - attributeData.setAttributeValue(utils.appendKey( - attributeValueData.getUserDataTypeValues(), "attributeValues", ",")); + attributeData.setAttributeValue( + utils.appendKey(attributeValueData.getUserDataTypeValues(), "attributeValues", ",")); } if (attributeData.getDatatypeBean().getShortName() != null) { @@ -162,16 +164,16 @@ public class DictionaryController { return null; } - @RequestMapping(value = {"/attribute_dictionary/remove_attribute"}, - method = {RequestMethod.POST}) - public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + @RequestMapping(value = {"/attribute_dictionary/remove_attribute"}, method = {RequestMethod.POST}) + public void removeAttributeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, attributeDatas, Attribute.class); } // OnapName Dictionary - @RequestMapping(value = {"/get_OnapNameDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_OnapNameDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getOnapNameDictionaryByNameEntityData(HttpServletResponse response) { LOGGER.info("get_OnapNameDataByName is called"); @@ -179,7 +181,9 @@ public class DictionaryController { utils.getDataByEntity(response, onapNameDatas, onapName, OnapName.class); } - @RequestMapping(value = {"/get_OnapNameData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_OnapNameData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getOnapNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -201,24 +205,21 @@ public class DictionaryController { onapData = mapper.readValue(root.get(dictionaryFields).toString(), OnapName.class); userId = "API"; } else { - onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), - OnapName.class); + onapData = mapper.readValue(root.get("onapNameDictionaryData").toString(), OnapName.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getOnapName(), - onapName, OnapName.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getOnapName(), onapName, OnapName.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { OnapName data = (OnapName) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -248,8 +249,7 @@ public class DictionaryController { } @RequestMapping(value = {"/onap_dictionary/remove_onap"}, method = {RequestMethod.POST}) - public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeOnapDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, onapNameDatas, OnapName.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java index b42731d61..f56da990c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportController.java @@ -21,16 +21,20 @@ package org.onap.policy.pap.xacml.rest.controller; import au.com.bytecode.opencsv.CSVReader; + import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.compress.utils.IOUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -68,7 +72,6 @@ import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; - @Controller public class DictionaryImportController { private static final Logger LOGGER = FlexLogger.getLogger(DictionaryImportController.class); @@ -92,8 +95,7 @@ public class DictionaryImportController { } @RequestMapping(value = {"/dictionary/import_dictionary"}, method = {RequestMethod.POST}) - public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void importDictionaryData(HttpServletRequest request, HttpServletResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); String userId = request.getParameter("userId"); @@ -273,8 +275,7 @@ public class DictionaryImportController { String[] rows = dictSheet.get(i); for (int j = 0; j < rows.length; j++) { if ("modelName".equalsIgnoreCase(dictSheet.get(0)[j]) - || "Optimization Service Model" - .equalsIgnoreCase(dictSheet.get(0)[j])) { + || "Optimization Service Model".equalsIgnoreCase(dictSheet.get(0)[j])) { attribute.setModelName(rows[j]); } if ("version".equalsIgnoreCase(dictSheet.get(0)[j]) diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java index 7cf12043c..8dda4ddc7 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryController.java @@ -23,13 +23,16 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.PrintWriter; import java.net.UnknownHostException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.jboss.netty.handler.ipfilter.CIDR; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -58,7 +61,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; - @Controller public class FirewallDictionaryController { @@ -95,7 +97,6 @@ public class FirewallDictionaryController { private static String fwTagPickerDatas = "fwTagPickerDictionaryDatas"; private static String fwTagDatas = "fwTagDictionaryDatas"; - @Autowired public FirewallDictionaryController(CommonClassDao commonClassDao) { FirewallDictionaryController.commonClassDao = commonClassDao; @@ -113,14 +114,18 @@ public class FirewallDictionaryController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_PrefixListDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PrefixListDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPrefixListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, pfListDatas, prefixListName, PrefixList.class); } - @RequestMapping(value = {"/get_PrefixListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PrefixListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPrefixListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -128,8 +133,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_prefixList"}, method = {RequestMethod.POST}) - public ModelAndView savePrefixListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -138,25 +143,21 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PrefixList prefixList; if (fromAPI) { - prefixList = - mapper.readValue(root.get(dictionaryFields).toString(), PrefixList.class); + prefixList = mapper.readValue(root.get(dictionaryFields).toString(), PrefixList.class); } else { - prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), - PrefixList.class); + prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - prefixList.getPrefixListName(), prefixListName, PrefixList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(prefixList.getPrefixListName(), + prefixListName, PrefixList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PrefixList data = (PrefixList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { prefixList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != prefixList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != prefixList.getId()))) { duplicateflag = true; } } @@ -167,8 +168,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(prefixList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class)); } else { responseString = duplicateResponseString; } @@ -191,15 +191,14 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/validate_prefixList"}, method = {RequestMethod.POST}) - public void validatePrefixListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void validatePrefixListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - PrefixList prefixList = mapper - .readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); + PrefixList prefixList = mapper.readValue(root.get("prefixListDictionaryData").toString(), PrefixList.class); String responseValidation = successMessage; try { CIDR.newCIDR(prefixList.getPrefixListValue()); @@ -219,7 +218,9 @@ public class FirewallDictionaryController { } } - @RequestMapping(value = {"/get_PortListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PortListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPortListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -227,8 +228,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_portName"}, method = {RequestMethod.POST}) - public ModelAndView savePortListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePortListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -239,21 +240,18 @@ public class FirewallDictionaryController { if (fromAPI) { portList = mapper.readValue(root.get(dictionaryFields).toString(), PortList.class); } else { - portList = mapper.readValue(root.get("portListDictionaryData").toString(), - PortList.class); + portList = mapper.readValue(root.get("portListDictionaryData").toString(), PortList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(portList.getPortName(), - "portName", PortList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(portList.getPortName(), "portName", PortList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PortList data = (PortList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { portList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != portList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != portList.getId()))) { duplicateflag = true; } } @@ -280,20 +278,23 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_PortList"}, method = {RequestMethod.POST}) - public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removePortListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, portListDatas, PortList.class); } - @RequestMapping(value = {"/get_ProtocolListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ProtocolListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getProtocolListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value = {"/get_ProtocolListDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ProtocolListDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getProtocolListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -301,8 +302,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_protocolList"}, method = {RequestMethod.POST}) - public ModelAndView saveProtocolListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -311,24 +312,20 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); ProtocolList protocolList; if (fromAPI) { - protocolList = - mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class); + protocolList = mapper.readValue(root.get(dictionaryFields).toString(), ProtocolList.class); } else { - protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), - ProtocolList.class); + protocolList = mapper.readValue(root.get("protocolListDictionaryData").toString(), ProtocolList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - protocolList.getProtocolName(), protocolName, ProtocolList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(protocolList.getProtocolName(), + protocolName, ProtocolList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ProtocolList data = (ProtocolList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { protocolList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != protocolList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != protocolList.getId()))) { duplicateflag = true; } } @@ -339,8 +336,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(protocolList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class)); } else { responseString = duplicateResponseString; } @@ -356,20 +352,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_protocol"}, method = {RequestMethod.POST}) - public void removeProtocolListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeProtocolListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, protocolListDatas, ProtocolList.class); } - @RequestMapping(value = {"/get_AddressGroupDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_AddressGroupDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getAddressGroupDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, addressGroupDatas, "name", AddressGroup.class); } - @RequestMapping(value = {"/get_AddressGroupData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_AddressGroupData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getAddressGroupDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -377,8 +377,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_addressGroup"}, method = {RequestMethod.POST}) - public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -388,32 +388,27 @@ public class FirewallDictionaryController { AddressGroup addressGroup; GridData gridData; if (fromAPI) { - addressGroup = - mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class); + addressGroup = mapper.readValue(root.get(dictionaryFields).toString(), AddressGroup.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(), - AddressGroup.class); - gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(), - GridData.class); + addressGroup = mapper.readValue(root.get("addressGroupDictionaryData").toString(), AddressGroup.class); + gridData = mapper.readValue(root.get("addressGroupDictionaryData").toString(), GridData.class); } if (!addressGroup.getGroupName().startsWith(groupNameStart)) { String groupName = groupNameStart + addressGroup.getGroupName(); addressGroup.setGroupName(groupName); } addressGroup.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(addressGroup.getGroupName(), "name", AddressGroup.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { AddressGroup data = (AddressGroup) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { addressGroup.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != addressGroup.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != addressGroup.getId()))) { duplicateflag = true; } } @@ -424,8 +419,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(addressGroup); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class)); } else { responseString = duplicateResponseString; } @@ -441,20 +435,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_AddressGroup"}, method = {RequestMethod.POST}) - public void removeAddressGroupDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeAddressGroupDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, addressGroupDatas, AddressGroup.class); } - @RequestMapping(value = {"/get_ActionListDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ActionListDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getActionListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, actionListDatas, "actionName", ActionList.class); } - @RequestMapping(value = {"/get_ActionListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ActionListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getActionListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -462,8 +460,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_ActionList"}, method = {RequestMethod.POST}) - public ModelAndView saveActionListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveActionListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -472,24 +470,20 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); ActionList actionList; if (fromAPI) { - actionList = - mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class); + actionList = mapper.readValue(root.get(dictionaryFields).toString(), ActionList.class); } else { - actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), - ActionList.class); + actionList = mapper.readValue(root.get("actionListDictionaryData").toString(), ActionList.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - actionList.getActionName(), "actionName", ActionList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(actionList.getActionName(), "actionName", ActionList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ActionList data = (ActionList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { actionList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != actionList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != actionList.getId()))) { duplicateflag = true; } } @@ -500,8 +494,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(actionList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class)); } else { responseString = duplicateResponseString; } @@ -523,14 +516,18 @@ public class FirewallDictionaryController { utils.removeData(request, response, actionListDatas, ActionList.class); } - @RequestMapping(value = {"/get_ServiceGroupData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ServiceGroupData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getServiceGroupDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value = {"/get_ServiceGroupDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ServiceGroupDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getServiceGroupDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -538,8 +535,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_serviceGroup"}, method = {RequestMethod.POST}) - public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -549,32 +546,28 @@ public class FirewallDictionaryController { GroupServiceList groupServiceList; GridData gridData; if (fromAPI) { - groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), - GroupServiceList.class); + groupServiceList = mapper.readValue(root.get(dictionaryFields).toString(), GroupServiceList.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - groupServiceList = mapper.readValue( - root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); - gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), - GridData.class); + groupServiceList = + mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GroupServiceList.class); + gridData = mapper.readValue(root.get("serviceGroupDictionaryData").toString(), GridData.class); } if (!groupServiceList.getGroupName().startsWith(groupNameStart)) { String groupName = groupNameStart + groupServiceList.getGroupName(); groupServiceList.setGroupName(groupName); } groupServiceList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - groupServiceList.getGroupName(), "name", GroupServiceList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(groupServiceList.getGroupName(), "name", GroupServiceList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { GroupServiceList data = (GroupServiceList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { groupServiceList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != groupServiceList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != groupServiceList.getId()))) { duplicateflag = true; } } @@ -585,8 +578,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(groupServiceList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class)); } else { responseString = duplicateResponseString; } @@ -602,20 +594,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_serviceGroup"}, method = {RequestMethod.POST}) - public void removeServiceGroupDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeServiceGroupDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, serviceGroupDatas, GroupServiceList.class); } - @RequestMapping(value = {"/get_SecurityZoneDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SecurityZoneDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSecurityZoneDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, securityZoneDatas, zoneName, SecurityZone.class); } - @RequestMapping(value = {"/get_SecurityZoneData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SecurityZoneData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSecurityZoneDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -623,8 +619,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_securityZone"}, method = {RequestMethod.POST}) - public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -633,24 +629,20 @@ public class FirewallDictionaryController { JsonNode root = mapper.readTree(request.getReader()); SecurityZone securityZone; if (fromAPI) { - securityZone = - mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class); + securityZone = mapper.readValue(root.get(dictionaryFields).toString(), SecurityZone.class); } else { - securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), - SecurityZone.class); + securityZone = mapper.readValue(root.get("securityZoneDictionaryData").toString(), SecurityZone.class); } - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(securityZone.getZoneName(), zoneName, SecurityZone.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { SecurityZone data = (SecurityZone) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { securityZone.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != securityZone.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != securityZone.getId()))) { duplicateflag = true; } } @@ -661,8 +653,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(securityZone); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class)); } else { responseString = duplicateResponseString; } @@ -678,21 +669,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_securityZone"}, method = {RequestMethod.POST}) - public void removeSecurityZoneDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeSecurityZoneDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, securityZoneDatas, SecurityZone.class); } - - @RequestMapping(value = {"/get_ServiceListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ServiceListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getServiceListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, serviceListDatas, ServiceList.class); } - @RequestMapping(value = {"/get_ServiceListDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ServiceListDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getServiceListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -700,8 +694,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_serviceList"}, method = {RequestMethod.POST}) - public ModelAndView saveServiceListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveServiceListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -711,33 +705,27 @@ public class FirewallDictionaryController { ServiceList serviceList; GridData serviceListGridData; if (fromAPI) { - serviceList = - mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class); - serviceListGridData = - mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); + serviceList = mapper.readValue(root.get(dictionaryFields).toString(), ServiceList.class); + serviceListGridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), - ServiceList.class); - serviceListGridData = mapper.readValue( - root.get("serviceListDictionaryData").toString(), GridData.class); + serviceList = mapper.readValue(root.get("serviceListDictionaryData").toString(), ServiceList.class); + serviceListGridData = + mapper.readValue(root.get("serviceListDictionaryData").toString(), GridData.class); } - serviceList.setServiceTransProtocol( - utils.appendKey(serviceListGridData.getTransportProtocols(), option, ",")); - serviceList.setServiceAppProtocol( - utils.appendKey(serviceListGridData.getAppProtocols(), option, ",")); + serviceList + .setServiceTransProtocol(utils.appendKey(serviceListGridData.getTransportProtocols(), option, ",")); + serviceList.setServiceAppProtocol(utils.appendKey(serviceListGridData.getAppProtocols(), option, ",")); serviceList.setServiceType("SERVICE"); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - serviceList.getServiceName(), serviceName, ServiceList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(serviceList.getServiceName(), serviceName, ServiceList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { ServiceList data = (ServiceList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { serviceList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != serviceList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != serviceList.getId()))) { duplicateflag = true; } } @@ -748,8 +736,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(serviceList); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class)); } else { responseString = duplicateResponseString; } @@ -765,20 +752,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_serviceList"}, method = {RequestMethod.POST}) - public void removeServiceListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeServiceListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, serviceListDatas, ServiceList.class); } - @RequestMapping(value = {"/get_ZoneData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ZoneData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getZoneDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, zoneDatas, Zone.class); } - @RequestMapping(value = {"/get_ZoneDictionaryDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_ZoneDictionaryDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getZoneDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -800,18 +791,15 @@ public class FirewallDictionaryController { } else { zone = mapper.readValue(root.get("zoneDictionaryData").toString(), Zone.class); } - List<Object> duplicateData = - commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(zone.getZoneName(), zoneName, Zone.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { Zone data = (Zone) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { zone.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != zone.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != zone.getId()))) { duplicateflag = true; } } @@ -838,20 +826,23 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_zone"}, method = {RequestMethod.POST}) - public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeZoneDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, zoneDatas, Zone.class); } - @RequestMapping(value = {"/get_TermListDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TermListDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTermListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, termListDictDatas, termName, TermList.class); } - @RequestMapping(value = {"/get_TermListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TermListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTermListDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -859,8 +850,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_termList"}, method = {RequestMethod.POST}) - public ModelAndView saveTermListDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveTermListDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -872,41 +863,33 @@ public class FirewallDictionaryController { String userId = null; if (fromAPI) { termList = mapper.readValue(root.get(dictionaryFields).toString(), TermList.class); - termListDatas = - mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class); + termListDatas = mapper.readValue(root.get(dictionaryFields).toString(), TermListData.class); userId = "API"; } else { - termList = mapper.readValue(root.get("termListDictionaryData").toString(), - TermList.class); - termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), - TermListData.class); + termList = mapper.readValue(root.get("termListDictionaryData").toString(), TermList.class); + termListDatas = mapper.readValue(root.get("termListDictionaryData").toString(), TermListData.class); userId = root.get(userid).textValue(); } termList.setFromZones(utils.appendKey(termListDatas.getFromZoneDatas(), option, ",")); termList.setToZones(utils.appendKey(termListDatas.getToZoneDatas(), option, ",")); termList.setSrcIPList(utils.appendKey(termListDatas.getSourceListDatas(), option, ",")); - termList.setDestIPList( - utils.appendKey(termListDatas.getDestinationListDatas(), option, ",")); - termList.setSrcPortList( - utils.appendKey(termListDatas.getSourceServiceDatas(), option, ",")); - termList.setDestPortList( - utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ",")); + termList.setDestIPList(utils.appendKey(termListDatas.getDestinationListDatas(), option, ",")); + termList.setSrcPortList(utils.appendKey(termListDatas.getSourceServiceDatas(), option, ",")); + termList.setDestPortList(utils.appendKey(termListDatas.getDestinationServiceDatas(), option, ",")); termList.setAction(utils.appendKey(termListDatas.getActionListDatas(), option, ",")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(termList.getTermName(), - termName, TermList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(termList.getTermName(), termName, TermList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { TermList data = (TermList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { termList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != termList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != termList.getId()))) { duplicateflag = true; } } @@ -936,22 +919,24 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_termList"}, method = {RequestMethod.POST}) - public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeTermListDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, termListDictDatas, TermList.class); } // ParentList Dictionary Data - @RequestMapping(value = {"/get_FWDictionaryListDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_FWDictionaryListDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getFWDictListDictionaryEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); - utils.getDataByEntity(response, fwDictListDatas, "parentItemName", - FirewallDictionaryList.class); + utils.getDataByEntity(response, fwDictListDatas, "parentItemName", FirewallDictionaryList.class); } - @RequestMapping(value = {"/get_FWDictionaryListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_FWDictionaryListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getFWDictionaryListEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -959,8 +944,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_FWDictionaryList"}, method = {RequestMethod.POST}) - public ModelAndView saveFWDictionaryList(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveFWDictionaryList(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -970,31 +955,27 @@ public class FirewallDictionaryController { FirewallDictionaryList fwDictList; GridData gridData; if (fromAPI) { - fwDictList = mapper.readValue(root.get(dictionaryFields).toString(), - FirewallDictionaryList.class); + fwDictList = mapper.readValue(root.get(dictionaryFields).toString(), FirewallDictionaryList.class); gridData = mapper.readValue(root.get(dictionaryFields).toString(), GridData.class); } else { - fwDictList = mapper.readValue(root.get("fwDictListDictionaryData").toString(), - FirewallDictionaryList.class); - gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), - GridData.class); + fwDictList = + mapper.readValue(root.get("fwDictListDictionaryData").toString(), FirewallDictionaryList.class); + gridData = mapper.readValue(root.get("fwDictListDictionaryData").toString(), GridData.class); } fwDictList.setServiceList(utils.appendKey(gridData.getAttributes(), option, ",")); fwDictList.setAddressList(utils.appendKey(gridData.getAlAttributes(), option, ",")); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - fwDictList.getParentItemName(), "parentItemName", FirewallDictionaryList.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwDictList.getParentItemName(), + "parentItemName", FirewallDictionaryList.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { FirewallDictionaryList data = (FirewallDictionaryList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { fwDictList.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != fwDictList.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != fwDictList.getId()))) { duplicateflag = true; } } @@ -1005,8 +986,7 @@ public class FirewallDictionaryController { } else { commonClassDao.update(fwDictList); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class)); } else { responseString = duplicateResponseString; } @@ -1021,23 +1001,24 @@ public class FirewallDictionaryController { return null; } - @RequestMapping(value = {"/fw_dictionary/remove_FWDictionaryList"}, - method = {RequestMethod.POST}) - public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response) - throws IOException { + @RequestMapping(value = {"/fw_dictionary/remove_FWDictionaryList"}, method = {RequestMethod.POST}) + public void removeFWDictionaryList(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwDictListDatas, FirewallDictionaryList.class); } - - @RequestMapping(value = {"/get_TagPickerNameByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TagPickerNameByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTagPickerNameEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, fwTagPickerDatas, tagPickerName, FWTagPicker.class); } - @RequestMapping(value = {"/get_TagPickerListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TagPickerListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTagPickerDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -1045,8 +1026,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/save_fwTagPicker"}, method = {RequestMethod.POST}) - public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -1057,33 +1038,28 @@ public class FirewallDictionaryController { TagGridValues data; String userId = ""; if (fromAPI) { - fwTagPicker = - mapper.readValue(root.get(dictionaryFields).toString(), FWTagPicker.class); + fwTagPicker = mapper.readValue(root.get(dictionaryFields).toString(), FWTagPicker.class); data = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); userId = "API"; } else { - fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), - FWTagPicker.class); - data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), - TagGridValues.class); + fwTagPicker = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), FWTagPicker.class); + data = mapper.readValue(root.get("fwTagPickerDictionaryData").toString(), TagGridValues.class); userId = root.get(userid).textValue(); } fwTagPicker.setTagValues(utils.appendKeyValue(data.getTags(), "#", ":")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - fwTagPicker.getTagPickerName(), tagPickerName, FWTagPicker.class); + List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTagPicker.getTagPickerName(), + tagPickerName, FWTagPicker.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { FWTagPicker data1 = (FWTagPicker) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { fwTagPicker.setId(data1.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data1.getId() != fwTagPicker.getId()))) { + || (request.getParameter(operation) == null && (data1.getId() != fwTagPicker.getId()))) { duplicateflag = true; } } @@ -1097,8 +1073,7 @@ public class FirewallDictionaryController { fwTagPicker.setModifiedDate(new Date()); commonClassDao.update(fwTagPicker); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class)); } else { responseString = duplicateResponseString; } @@ -1114,30 +1089,33 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_tagPicker"}, method = {RequestMethod.POST}) - public void removeFirewallTagPickerDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeFirewallTagPickerDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwTagPickerDatas, FWTagPicker.class); } - @RequestMapping(value = {"/get_TagListData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TagListData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTagDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, fwTagDatas, FWTag.class); } - @RequestMapping(value = {"/get_TagNameByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_TagNameByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getTagNameEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, fwTagDatas, "fwTagName", FWTag.class); } - @RequestMapping(value = {"/fw_dictionary/save_fwTag"}, method = {RequestMethod.POST}) - public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -1149,30 +1127,26 @@ public class FirewallDictionaryController { String userId = ""; if (fromAPI) { fwTag = mapper.readValue(root.get(dictionaryFields).toString(), FWTag.class); - tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), - TagGridValues.class); + tagGridValues = mapper.readValue(root.get(dictionaryFields).toString(), TagGridValues.class); userId = "API"; } else { fwTag = mapper.readValue(root.get("fwTagDictionaryData").toString(), FWTag.class); - tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), - TagGridValues.class); + tagGridValues = mapper.readValue(root.get("fwTagDictionaryData").toString(), TagGridValues.class); userId = root.get(userid).textValue(); } fwTag.setTagValues(utils.appendKey(tagGridValues.getTags(), "tags", ",")); UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), - "fwTagName", FWTag.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(fwTag.getFwTagName(), "fwTagName", FWTag.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { FWTag data = (FWTag) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { fwTag.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != fwTag.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != fwTag.getId()))) { duplicateflag = true; } } @@ -1202,8 +1176,8 @@ public class FirewallDictionaryController { } @RequestMapping(value = {"/fw_dictionary/remove_tagList"}, method = {RequestMethod.POST}) - public void removeFirewallTagDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removeFirewallTagDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, fwTagDatas, FWTag.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java index ee274d2a7..1582dab19 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryController.java @@ -24,6 +24,7 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; + import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -32,8 +33,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.lang.StringUtils; import org.json.JSONObject; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -74,9 +77,7 @@ public class MicroServiceDictionaryController { private static String dictionaryDBQuery = "dictionaryDBQuery"; private LinkedHashMap<String, MSAttributeObject> classMap; private List<String> modelList = new ArrayList<>(); - private static String apiflag = "apiflag"; private static String dictionaryFields = "dictionaryFields"; - private static String update = "update"; private static String duplicateResponseString = "Duplicate"; private static String microServiceModelsDictionaryDatas = "microServiceModelsDictionaryDatas"; private static String modelName = "modelName"; @@ -112,14 +113,18 @@ public class MicroServiceDictionaryController { private MicroServiceModels newModel; - @RequestMapping(value = {"/get_DCAEUUIDDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_DCAEUUIDDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDCAEUUIDDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, dcaeUUIDDatas, "name", DCAEuuid.class); } - @RequestMapping(value = {"/get_DCAEUUIDData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_DCAEUUIDData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getDCAEUUIDDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -182,21 +187,27 @@ public class MicroServiceDictionaryController { utils.removeData(request, response, dcaeUUIDDatas, DCAEuuid.class); } - @RequestMapping(value = {"/get_MicroServiceConfigNameDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceConfigNameDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceConfigNameByNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceConfigNameDatas, "name", MicroServiceConfigName.class); } - @RequestMapping(value = {"/get_MicroServiceConfigNameData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceConfigNameData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceConfigNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, microServiceConfigNameDatas, MicroServiceConfigName.class); } - @RequestMapping(value = {"/get_MicroServiceDictData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceDictData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceDictNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -330,14 +341,18 @@ public class MicroServiceDictionaryController { utils.removeData(request, response, microServiceConfigNameDatas, MicroServiceConfigName.class); } - @RequestMapping(value = {"/get_MicroServiceLocationDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceLocationDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceLocationByNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceLocationDatas, "name", MicroServiceLocation.class); } - @RequestMapping(value = {"/get_MicroServiceLocationData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceLocationData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceLocationDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -405,14 +420,18 @@ public class MicroServiceDictionaryController { utils.removeData(request, response, microServiceLocationDatas, MicroServiceLocation.class); } - @RequestMapping(value = {"/get_MicroServiceAttributeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceAttributeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceAttributeByNameDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceAttributeDatas, "name", MicroServiceAttribute.class); } - @RequestMapping(value = {"/get_MicroServiceAttributeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceAttributeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceAttributeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -483,15 +502,18 @@ public class MicroServiceDictionaryController { utils.removeData(request, response, microServiceAttributeDatas, MicroServiceAttribute.class); } - - @RequestMapping(value = {"/get_MicroServiceModelsDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceModelsDictionaryDatas, modelName, MicroServiceModels.class); } - @RequestMapping(value = {"/get_MicroServiceModelsDataByVersion"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsDataByVersion"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryByVersionEntityData(HttpServletRequest request, HttpServletResponse response) { @@ -517,14 +539,18 @@ public class MicroServiceDictionaryController { } } - @RequestMapping(value = {"/get_MicroServiceModelsData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, microServiceModelsDictionaryDatas, MicroServiceModels.class); } - @RequestMapping(value = {"/get_MicroServiceModelsDataServiceVersion"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsDataServiceVersion"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryEntityDataServiceVersion(HttpServletResponse response) { try { @@ -552,7 +578,9 @@ public class MicroServiceDictionaryController { } } - @RequestMapping(value = {"/get_MicroServiceModelsDataByClass"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceModelsDataByClass"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceModelsDictionaryClassEntityData(HttpServletResponse response) { try { @@ -800,21 +828,24 @@ public class MicroServiceDictionaryController { return returnList; } - @RequestMapping(value = {"/get_MicroServiceHeaderDefaultsDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceHeaderDefaultsDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceHeaderDefaultsEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, microServiceHeaderDefaultDatas, "modelName", MicroserviceHeaderdeFaults.class); } - @RequestMapping(value = {"/get_MicroServiceHeaderDefaultsData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_MicroServiceHeaderDefaultsData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getMicroServiceHeaderDefaultsEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, microServiceHeaderDefaultDatas, MicroserviceHeaderdeFaults.class); } - @RequestMapping(value = {"/ms_dictionary/save_headerDefaults"}, method = {RequestMethod.POST}) public ModelAndView saveMicroServiceHeaderDefaultValues(HttpServletRequest request, HttpServletResponse response) throws IOException { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java index 3d1dba905..52394bab0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,8 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.Gson; + import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; @@ -46,18 +52,13 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.Gson; - @Controller public class OptimizationDictionaryController { private static CommonClassDao commonClassDao; private static String operation = "operation"; - private LinkedHashMap<String,MSAttributeObject > classMap; - private static String dictionaryFields ="dictionaryFields"; + private LinkedHashMap<String, MSAttributeObject> classMap; + private static String dictionaryFields = "dictionaryFields"; private static String duplicateResponseString = "Duplicate"; private static String optimizationModelsDictionaryDatas = "optimizationModelsDictionaryDatas"; private static String modelName = "modelName"; @@ -67,19 +68,19 @@ public class OptimizationDictionaryController { private static String classMapData = "classMap"; private static final String UPDATE = "update"; - - public OptimizationDictionaryController(){ + public OptimizationDictionaryController() { super(); - } + } - private DictionaryUtils getDictionaryUtilsInstance(){ + private DictionaryUtils getDictionaryUtilsInstance() { return DictionaryUtils.getDictionaryUtils(); } - + @Autowired - public OptimizationDictionaryController(CommonClassDao commonClassDao){ + public OptimizationDictionaryController(CommonClassDao commonClassDao) { setCommonClassDao(commonClassDao); } + public static void setCommonClassDao(CommonClassDao commonClassDao) { OptimizationDictionaryController.commonClassDao = commonClassDao; } @@ -88,20 +89,27 @@ public class OptimizationDictionaryController { private OptimizationModels newModel; - @RequestMapping(value={"/get_OptimizationModelsData"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getOptimizationModelsDictionaryEntityData(HttpServletResponse response){ + @RequestMapping( + value = {"/get_OptimizationModelsData"}, + method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getOptimizationModelsDictionaryEntityData(HttpServletResponse response) { DictionaryUtils dUtils = getDictionaryUtilsInstance(); dUtils.getData(response, optimizationModelsDictionaryDatas, OptimizationModels.class); } - @RequestMapping(value={"/get_OptimizationModelsDataByName"}, method={RequestMethod.GET} , produces=MediaType.APPLICATION_JSON_VALUE) - public void getOptimizationModelsDictionaryByNameEntityData(HttpServletResponse response){ + @RequestMapping( + value = {"/get_OptimizationModelsDataByName"}, + method = {RequestMethod.GET}, + produces = MediaType.APPLICATION_JSON_VALUE) + public void getOptimizationModelsDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils dUtils = getDictionaryUtilsInstance(); dUtils.getDataByEntity(response, optimizationModelsDictionaryDatas, modelName, OptimizationModels.class); } - @RequestMapping(value={"/oof_dictionary/save_model"}, method={RequestMethod.POST}) - public ModelAndView saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException{ + @RequestMapping(value = {"/oof_dictionary/save_model"}, method = {RequestMethod.POST}) + public ModelAndView saveOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils dUtils = getDictionaryUtilsInstance(); try { this.newModel = new OptimizationModels(); @@ -113,24 +121,27 @@ public class OptimizationDictionaryController { String userId = null; String dataOrderInfo = null; - if(root.has("dataOrderInfo")){ + if (root.has("dataOrderInfo")) { dataOrderInfo = root.get("dataOrderInfo").toString(); } - if(root.has("modelType")){ + if (root.has("modelType")) { JsonNode dataType = root.get("modelType"); - String modelType= dataType.toString(); - if(modelType.contains("yml")){ - if (root.has(optimizationModelsDictionaryData)){ - if (root.get(optimizationModelsDictionaryData).has(description)){ - optimizationModels.setDescription(root.get(optimizationModelsDictionaryData).get(description).asText().replace("\"", "")); + String modelType = dataType.toString(); + if (modelType.contains("yml")) { + if (root.has(optimizationModelsDictionaryData)) { + if (root.get(optimizationModelsDictionaryData).has(description)) { + optimizationModels.setDescription(root.get(optimizationModelsDictionaryData) + .get(description).asText().replace("\"", "")); } - if (root.get(optimizationModelsDictionaryData).has(modelName)){ - optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName).asText().replace("\"", "")); + if (root.get(optimizationModelsDictionaryData).has(modelName)) { + optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName) + .asText().replace("\"", "")); this.newModel.setModelName(optimizationModels.getModelName()); } - if (root.get(optimizationModelsDictionaryData).has(version)){ - optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", "")); + if (root.get(optimizationModelsDictionaryData).has(version)) { + optimizationModels.setVersion( + root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", "")); this.newModel.setVersion(optimizationModels.getVersion()); } } @@ -138,13 +149,13 @@ public class OptimizationDictionaryController { classMap = new LinkedHashMap<>(); JsonNode data = root.get(classMapData); ObjectMapper mapper1 = new ObjectMapper(); - String data1 = data.toString().substring(1, data.toString().length()-1); + String data1 = data.toString().substring(1, data.toString().length() - 1); data1 = data1.replace("\\", ""); - data1=data1.replace("\"{","{"); - data1=data1.replace("}\"","}"); + data1 = data1.replace("\"{", "{"); + data1 = data1.replace("}\"", "}"); JSONObject jsonObject = new JSONObject(data1); Set<String> keys = jsonObject.keySet(); - for(String key : keys){ + for (String key : keys) { String value = jsonObject.get(key).toString(); MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); classMap.put(key, msAttributeObject); @@ -155,44 +166,51 @@ public class OptimizationDictionaryController { this.newModel.setDependency("[]"); String value = new Gson().toJson(mainClass.getSubClass()); this.newModel.setSubattributes(value); - String attributes= mainClass.getAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndexForAttributes= attributes.indexOf('='); - String atttributesAfterFirstEquals= attributes.substring(equalsIndexForAttributes+1, attributes.length()-1); + String attributes = mainClass.getAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndexForAttributes = attributes.indexOf('='); + String atttributesAfterFirstEquals = + attributes.substring(equalsIndexForAttributes + 1, attributes.length() - 1); this.newModel.setAttributes(atttributesAfterFirstEquals); - String refAttributes= mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); - int equalsIndex= refAttributes.indexOf('='); - String refAttributesAfterFirstEquals= refAttributes.substring(equalsIndex+1, refAttributes.length()-1); + String refAttributes = mainClass.getRefAttribute().toString().replace("{", "").replace("}", ""); + int equalsIndex = refAttributes.indexOf('='); + String refAttributesAfterFirstEquals = + refAttributes.substring(equalsIndex + 1, refAttributes.length() - 1); this.newModel.setRefattributes(refAttributesAfterFirstEquals); this.newModel.setEnumValues(mainClass.getEnumType().toString().replace("{", "").replace("}", "")); - this.newModel.setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); + this.newModel + .setAnnotation(mainClass.getMatchingSet().toString().replace("{", "").replace("}", "")); - }else{ + } else { if (fromAPI) { - optimizationModels = mapper.readValue(root.get(dictionaryFields).toString(), OptimizationModels.class); + optimizationModels = + mapper.readValue(root.get(dictionaryFields).toString(), OptimizationModels.class); userId = "API"; } else { - if (root.has(optimizationModelsDictionaryData)){ - if (root.get(optimizationModelsDictionaryData).has(description)){ - optimizationModels.setDescription(root.get(optimizationModelsDictionaryData).get(description).asText().replace("\"", "")); + if (root.has(optimizationModelsDictionaryData)) { + if (root.get(optimizationModelsDictionaryData).has(description)) { + optimizationModels.setDescription(root.get(optimizationModelsDictionaryData) + .get(description).asText().replace("\"", "")); } - if (root.get(optimizationModelsDictionaryData).has(modelName)){ - optimizationModels.setModelName(root.get(optimizationModelsDictionaryData).get(modelName).asText().replace("\"", "")); + if (root.get(optimizationModelsDictionaryData).has(modelName)) { + optimizationModels.setModelName(root.get(optimizationModelsDictionaryData) + .get(modelName).asText().replace("\"", "")); this.newModel.setModelName(optimizationModels.getModelName()); } - if (root.get(optimizationModelsDictionaryData).has(version)){ - optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version).asText().replace("\"", "")); + if (root.get(optimizationModelsDictionaryData).has(version)) { + optimizationModels.setVersion(root.get(optimizationModelsDictionaryData).get(version) + .asText().replace("\"", "")); this.newModel.setVersion(optimizationModels.getVersion()); } } - if(root.has(classMapData)){ + if (root.has(classMapData)) { classMap = new LinkedHashMap<>(); JsonNode data = root.get(classMapData); ObjectMapper mapper1 = new ObjectMapper(); - String data1 = data.toString().substring(1, data.toString().length()-1); + String data1 = data.toString().substring(1, data.toString().length() - 1); data1 = data1.replace("\\", ""); JSONObject jsonObject = new JSONObject(data1); Set<String> keys = jsonObject.keySet(); - for(String key : keys){ + for (String key : keys) { String value = jsonObject.get(key).toString(); MSAttributeObject msAttributeObject = mapper1.readValue(value, MSAttributeObject.class); classMap.put(key, msAttributeObject); @@ -212,80 +230,83 @@ public class OptimizationDictionaryController { optimizationModels.setEnumValues(this.newModel.getEnumValues()); optimizationModels.setAnnotation(this.newModel.getAnnotation()); - if(dataOrderInfo != null){ + if (dataOrderInfo != null) { optimizationModels.setDataOrderInfo(dataOrderInfo); } String checkName = optimizationModels.getModelName() + ":" + optimizationModels.getVersion(); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(checkName, "modelName:version", OptimizationModels.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(checkName, "modelName:version", OptimizationModels.class); boolean duplicateflag = false; - if(duplicateData!=null && !duplicateData.isEmpty()){ + if (duplicateData != null && !duplicateData.isEmpty()) { OptimizationModels data = (OptimizationModels) duplicateData.get(0); - if(request.getParameter(operation) != null && UPDATE.equals(request.getParameter(operation))){ + if (request.getParameter(operation) != null && UPDATE.equals(request.getParameter(operation))) { optimizationModels.setId(data.getId()); - }else if((request.getParameter(operation) != null && !UPDATE.equals(request.getParameter(operation))) || - (request.getParameter(operation) == null && (data.getId() != optimizationModels.getId()))){ + } else if ((request.getParameter(operation) != null && !UPDATE.equals(request.getParameter(operation))) + || (request.getParameter(operation) == null && (data.getId() != optimizationModels.getId()))) { duplicateflag = true; } } UserInfo userInfo = dUtils.getUserInfo(userId); String responseString = null; - if(!duplicateflag){ + if (!duplicateflag) { optimizationModels.setUserCreatedBy(userInfo); - if(optimizationModels.getId() == 0){ + if (optimizationModels.getId() == 0) { commonClassDao.save(optimizationModels); - }else{ + } else { commonClassDao.update(optimizationModels); } responseString = mapper.writeValueAsString(commonClassDao.getData(OptimizationModels.class)); - }else{ + } else { responseString = duplicateResponseString; } - if(fromAPI){ + if (fromAPI) { return dUtils.getResultForApi(responseString); - }else{ + } else { dUtils.setResponseData(response, optimizationModelsDictionaryDatas, responseString); } - }catch (Exception e){ + } catch (Exception e) { dUtils.setErrorResponseData(response, e); } return null; } - @RequestMapping(value={"/oof_dictionary/remove_model"}, method={RequestMethod.POST}) - public void removeOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/oof_dictionary/remove_model"}, method = {RequestMethod.POST}) + public void removeOptimizationModelsDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils dUtils = getDictionaryUtilsInstance(); dUtils.removeData(request, response, optimizationModelsDictionaryDatas, OptimizationModels.class); } - private void addValuesToNewModel(HashMap<String,MSAttributeObject > classMap) { - //Loop through the classmap and pull out the required info for the new file. + private void addValuesToNewModel(HashMap<String, MSAttributeObject> classMap) { + // Loop through the classmap and pull out the required info for the new file. String subAttribute = null; MSAttributeObject mainClass = classMap.get(this.newModel.getModelName()); - if (mainClass !=null){ - String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[]{"[", "]", " "}, new String[]{"", "", ""}); + if (mainClass != null) { + String dependTemp = StringUtils.replaceEach(mainClass.getDependency(), new String[] {"[", "]", " "}, + new String[] {"", "", ""}); ArrayList<String> dependency = new ArrayList<>(Arrays.asList(dependTemp.split(","))); dependency = getFullDependencyList(dependency); - for (String element : dependency){ + for (String element : dependency) { MSAttributeObject temp = classMap.get(element); - if (temp!=null){ + if (temp != null) { mainClass.addAllRefAttribute(temp.getRefAttribute()); mainClass.addAllAttribute(temp.getAttribute()); } } subAttribute = utils.createSubAttributes(dependency, classMap, this.newModel.getModelName()); - }else{ + } else { subAttribute = "{}"; this.newModel.setDependency(""); } - if (mainClass != null && mainClass.getDependency()==null){ + if (mainClass != null && mainClass.getDependency() == null) { mainClass.setDependency(""); } - if(mainClass != null){ + if (mainClass != null) { this.newModel.setDependency(mainClass.getDependency()); this.newModel.setSubattributes(subAttribute); this.newModel.setAttributes(mainClass.getAttribute().toString().replace("{", "").replace("}", "")); @@ -299,13 +320,14 @@ public class OptimizationDictionaryController { ArrayList<String> returnList = new ArrayList<>(); ArrayList<String> workingList; returnList.addAll(dependency); - for (String element : dependency ){ - if (classMap.containsKey(element)){ + for (String element : dependency) { + if (classMap.containsKey(element)) { MSAttributeObject value = classMap.get(element); - String rawValue = StringUtils.replaceEach(value.getDependency(), new String[]{"[", "]"}, new String[]{"", ""}); + String rawValue = + StringUtils.replaceEach(value.getDependency(), new String[] {"[", "]"}, new String[] {"", ""}); workingList = new ArrayList<>(Arrays.asList(rawValue.split(","))); - for(String depend : workingList){ - if (!returnList.contains(depend) && !depend.isEmpty()){ + for (String depend : workingList) { + if (!returnList.contains(depend) && !depend.isEmpty()) { returnList.add(depend.trim()); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java index c0e7729db..a230ebe38 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.ArrayList; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -49,8 +52,7 @@ import org.springframework.web.servlet.ModelAndView; @Controller public class PolicyScopeDictionaryController { - private static final Logger LOGGER = - FlexLogger.getLogger(PolicyScopeDictionaryController.class); + private static final Logger LOGGER = FlexLogger.getLogger(PolicyScopeDictionaryController.class); private static CommonClassDao commonClassDao; private static String operation = "operation"; @@ -81,24 +83,27 @@ public class PolicyScopeDictionaryController { PolicyScopeDictionaryController.commonClassDao = commonClassDao; } - @RequestMapping(value = {"/get_GroupPolicyScopeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_GroupPolicyScopeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getGroupPolicyScopeEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, groupPolicyScopeDatas, "name", GroupPolicyScopeList.class); } - @RequestMapping(value = {"/get_GroupPolicyScopeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_GroupPolicyScopeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getGroupPolicyScopeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, groupPolicyScopeDatas, GroupPolicyScopeList.class); } - @RequestMapping(value = {"/ps_dictionary/save_psGroupPolicyScope"}, - method = {RequestMethod.POST}) - public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/save_psGroupPolicyScope"}, method = {RequestMethod.POST}) + public ModelAndView savePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -109,40 +114,33 @@ public class PolicyScopeDictionaryController { GroupPolicyScope groupData = null; boolean duplicateGroupFlag = false; if (fromAPI) { - gpdata = mapper.readValue(root.get(dictionaryFields).toString(), - GroupPolicyScopeList.class); + gpdata = mapper.readValue(root.get(dictionaryFields).toString(), GroupPolicyScopeList.class); try { - groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), - GroupPolicyScope.class); + groupData = + mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); } catch (Exception e) { groupData = new GroupPolicyScope(); - groupData.setResource(root.get(dictionaryFields).get("resource").toString() - .replace("\"", "")); - groupData.setClosedloop(root.get(dictionaryFields).get("closedloop").toString() - .replace("\"", "")); - groupData.setService( - root.get(dictionaryFields).get("service").toString().replace("\"", "")); - groupData.setType( - root.get(dictionaryFields).get("type").toString().replace("\"", "")); + groupData.setResource(root.get(dictionaryFields).get("resource").toString().replace("\"", "")); + groupData.setClosedloop(root.get(dictionaryFields).get("closedloop").toString().replace("\"", "")); + groupData.setService(root.get(dictionaryFields).get("service").toString().replace("\"", "")); + groupData.setType(root.get(dictionaryFields).get("type").toString().replace("\"", "")); LOGGER.error(e); } } else { - gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), - GroupPolicyScopeList.class); + gpdata = mapper.readValue(root.get("groupPolicyScopeListData").toString(), GroupPolicyScopeList.class); try { - groupData = mapper.readValue(root.get(groupPolicyScopeListData1).toString(), - GroupPolicyScope.class); + groupData = + mapper.readValue(root.get(groupPolicyScopeListData1).toString(), GroupPolicyScope.class); } catch (Exception e) { LOGGER.error(e); groupData = new GroupPolicyScope(); - groupData.setResource(root.get(groupPolicyScopeListData1).get("resource") - .toString().replace("\"", "")); - groupData.setClosedloop(root.get(groupPolicyScopeListData1).get("closedloop") - .toString().replace("\"", "")); - groupData.setService(root.get(groupPolicyScopeListData1).get("service") - .toString().replace("\"", "")); - groupData.setType(root.get(groupPolicyScopeListData1).get("type").toString() - .replace("\"", "")); + groupData.setResource( + root.get(groupPolicyScopeListData1).get("resource").toString().replace("\"", "")); + groupData.setClosedloop( + root.get(groupPolicyScopeListData1).get("closedloop").toString().replace("\"", "")); + groupData.setService( + root.get(groupPolicyScopeListData1).get("service").toString().replace("\"", "")); + groupData.setType(root.get(groupPolicyScopeListData1).get("type").toString().replace("\"", "")); } } if (!gpdata.getGroupName().startsWith(policyScope)) { @@ -158,15 +156,15 @@ public class PolicyScopeDictionaryController { valueList.add("service=" + serviceValue); valueList.add("type=" + typeValue); valueList.add("closedLoopControlName=" + closedLoopValue); - String list = StringUtils.replaceEach(valueList.toString(), - new String[] {"[", "]", " "}, new String[] {"", "", ""}); + String list = StringUtils.replaceEach(valueList.toString(), new String[] {"[", "]", " "}, + new String[] {"", "", ""}); gpdata.setGroupList(list); - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), - "name", GroupPolicyScopeList.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(gpdata.getGroupName(), "name", GroupPolicyScopeList.class); if (duplicateData.isEmpty()) { - duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), - "groupList", GroupPolicyScopeList.class); + duplicateData = commonClassDao.checkDuplicateEntry(gpdata.getGroupList(), "groupList", + GroupPolicyScopeList.class); if (duplicateData.isEmpty()) { duplicateGroupFlag = true; } @@ -174,13 +172,11 @@ public class PolicyScopeDictionaryController { boolean duplicateflag = false; if (!duplicateData.isEmpty()) { GroupPolicyScopeList data = (GroupPolicyScopeList) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { gpdata.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != gpdata.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != gpdata.getId()))) { duplicateflag = true; } } @@ -191,8 +187,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(gpdata); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class)); } else if (duplicateGroupFlag) { responseString = "DuplicateGroup"; } else { @@ -209,22 +204,25 @@ public class PolicyScopeDictionaryController { return null; } - @RequestMapping(value = {"/ps_dictionary/remove_GroupPolicyScope"}, - method = {RequestMethod.POST}) - public void removePSGroupScopeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/ps_dictionary/remove_GroupPolicyScope"}, method = {RequestMethod.POST}) + public void removePSGroupScopeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, groupPolicyScopeDatas, GroupPolicyScopeList.class); } - @RequestMapping(value = {"/get_PSClosedLoopDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSClosedLoopDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSClosedLoopEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psCLDatas, "name", OnapName.class); } - @RequestMapping(value = {"/get_PSClosedLoopData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSClosedLoopData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSClosedLoopEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -232,8 +230,8 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/save_psClosedLoop"}, method = {RequestMethod.POST}) - public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -242,25 +240,22 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeClosedLoop onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), - PolicyScopeClosedLoop.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeClosedLoop.class); } else { onapData = mapper.readValue(root.get("psClosedLoopDictionaryData").toString(), PolicyScopeClosedLoop.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), - "name", PolicyScopeClosedLoop.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeClosedLoop.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PolicyScopeClosedLoop data = (PolicyScopeClosedLoop) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -271,8 +266,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(onapData); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class)); } else { responseString = duplicateResponseString; } @@ -288,20 +282,24 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/remove_PSClosedLoop"}, method = {RequestMethod.POST}) - public void removePSClosedLoopDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public void removePSClosedLoopDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psCLDatas, PolicyScopeClosedLoop.class); } - @RequestMapping(value = {"/get_PSServiceDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSServiceDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSServiceEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psServiceDatas, "name", PolicyScopeService.class); } - @RequestMapping(value = {"/get_PSServiceData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSServiceData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSServiceEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -309,8 +307,8 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/save_psService"}, method = {RequestMethod.POST}) - public ModelAndView savePSServiceDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -319,25 +317,21 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeService onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), - PolicyScopeService.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeService.class); } else { - onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), - PolicyScopeService.class); + onapData = mapper.readValue(root.get("psServiceDictionaryData").toString(), PolicyScopeService.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), - "name", PolicyScopeService.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeService.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PolicyScopeService data = (PolicyScopeService) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -348,8 +342,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(onapData); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class)); } else { responseString = duplicateResponseString; } @@ -365,20 +358,23 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/remove_PSService"}, method = {RequestMethod.POST}) - public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removePSServiceDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psServiceDatas, PolicyScopeService.class); } - @RequestMapping(value = {"/get_PSTypeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSTypeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSTypeEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psTypeDatas, "name", PolicyScopeType.class); } - @RequestMapping(value = {"/get_PSTypeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSTypeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSTypeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -386,8 +382,8 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/save_psType"}, method = {RequestMethod.POST}) - public ModelAndView savePSTypeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -396,25 +392,21 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeType onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), - PolicyScopeType.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeType.class); } else { - onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(), - PolicyScopeType.class); + onapData = mapper.readValue(root.get("psTypeDictionaryData").toString(), PolicyScopeType.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), - "name", PolicyScopeType.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeType.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PolicyScopeType data = (PolicyScopeType) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -425,8 +417,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(onapData); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class)); } else { responseString = duplicateResponseString; } @@ -442,20 +433,23 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/remove_PSType"}, method = {RequestMethod.POST}) - public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removePSTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, psTypeDatas, PolicyScopeType.class); } - @RequestMapping(value = {"/get_PSResourceDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSResourceDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSResourceEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, psResourceDatas, "name", PolicyScopeResource.class); } - @RequestMapping(value = {"/get_PSResourceData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_PSResourceData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getPSResourceEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -463,8 +457,8 @@ public class PolicyScopeDictionaryController { } @RequestMapping(value = {"/ps_dictionary/save_psResource"}, method = {RequestMethod.POST}) - public ModelAndView savePSResourceDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView savePSResourceDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -473,25 +467,21 @@ public class PolicyScopeDictionaryController { JsonNode root = mapper.readTree(request.getReader()); PolicyScopeResource onapData; if (fromAPI) { - onapData = mapper.readValue(root.get(dictionaryFields).toString(), - PolicyScopeResource.class); + onapData = mapper.readValue(root.get(dictionaryFields).toString(), PolicyScopeResource.class); } else { - onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), - PolicyScopeResource.class); + onapData = mapper.readValue(root.get("psResourceDictionaryData").toString(), PolicyScopeResource.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry(onapData.getName(), - "name", PolicyScopeResource.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(onapData.getName(), "name", PolicyScopeResource.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { PolicyScopeResource data = (PolicyScopeResource) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { onapData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != onapData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != onapData.getId()))) { duplicateflag = true; } } @@ -502,8 +492,7 @@ public class PolicyScopeDictionaryController { } else { commonClassDao.update(onapData); } - responseString = mapper - .writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class)); } else { responseString = duplicateResponseString; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java index 17fce7142..b7b63a9e0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyController.java @@ -24,6 +24,7 @@ import com.att.research.xacml.api.pap.PAPException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; @@ -32,9 +33,11 @@ import java.io.ObjectOutputStream; import java.net.URI; import java.util.List; import java.util.UUID; + import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -93,8 +96,8 @@ public class PushPolicyController { LOGGER.info("No request ID provided, sending generated ID: " + requestID); } LOGGER.info("Push policy Request to get the selectedPolicy : " + root.asText()); - String policyVersionName = policyScope.replace(".", File.separator) + File.separator - + filePrefix + policyName; + String policyVersionName = + policyScope.replace(".", File.separator) + File.separator + filePrefix + policyName; List<?> policyVersionObject = commonClassDao.getDataById(PolicyVersion.class, policyNames, policyVersionName); if (policyVersionObject != null) { @@ -120,10 +123,10 @@ public class PushPolicyController { } private void addPolicyToGroup(String policyScope, String policyID, String policyName, String pdpGroup, - HttpServletResponse response) { + HttpServletResponse response) { StdPDPGroup selectedPDPGroup = null; StdPDPPolicy selectedPolicy = null; - //Get the selected PDP Group to push the policy + // Get the selected PDP Group to push the policy try { selectedPDPGroup = (StdPDPGroup) XACMLPapServlet.getPAPEngine().getGroup(pdpGroup); } catch (PAPException e1) { @@ -147,16 +150,15 @@ public class PushPolicyController { params.put("scope", policyScope); params.put(policyNames, policyName.substring(policyScope.length() + 1)); List<?> createPolicyQueryList = commonClassDao.getDataByQuery(createPolicyQuery, params); - LOGGER.info("addPolicyToGroup:Total execution time to retrieve " + policyNames - + " from PolicyEntity"); + LOGGER.info("addPolicyToGroup:Total execution time to retrieve " + policyNames + " from PolicyEntity"); PolicyEntity policyEntity = null; if (!createPolicyQueryList.isEmpty()) { policyEntity = (PolicyEntity) createPolicyQueryList.get(0); } else { PolicyLogger - .error("Somehow, more than one policy with the same scope, name, and deleted status were found in" + - " the database"); + .error("Somehow, more than one policy with the same scope, name, and deleted status were found in" + + " the database"); String message = "Unknown Policy '" + policyName + "'"; PolicyLogger.error(MessageCodes.ERROR_DATA_ISSUE + " " + message); response.addHeader(errorMsg, "unknownPolicy"); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java index 6e794d966..d7683fa0b 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyController.java @@ -23,11 +23,14 @@ package org.onap.policy.pap.xacml.rest.controller; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.util.Date; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.RiskType; @@ -66,14 +69,18 @@ public class SafePolicyController { return DictionaryUtils.getDictionaryUtils(); } - @RequestMapping(value = {"/get_RiskTypeDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_RiskTypeDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getRiskTypeDictionaryByNameEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, riskTypeDatas, "name", RiskType.class); } - @RequestMapping(value = {"/get_RiskTypeData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_RiskTypeData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getRiskTypeDictionaryEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); @@ -81,8 +88,8 @@ public class SafePolicyController { } @RequestMapping(value = {"/sp_dictionary/save_riskType"}, method = {RequestMethod.POST}) - public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + public ModelAndView saveRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -92,27 +99,23 @@ public class SafePolicyController { RiskType riskTypeData; String userId = null; if (fromAPI) { - riskTypeData = - mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class); + riskTypeData = mapper.readValue(root.get("dictionaryFields").toString(), RiskType.class); userId = "API"; } else { - riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), - RiskType.class); + riskTypeData = mapper.readValue(root.get("riskTypeDictionaryData").toString(), RiskType.class); userId = root.get("userid").textValue(); } UserInfo userInfo = utils.getUserInfo(userId); - List<Object> duplicateData = commonClassDao - .checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(riskTypeData.getRiskName(), "name", RiskType.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { RiskType data = (RiskType) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { riskTypeData.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != riskTypeData.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != riskTypeData.getId()))) { duplicateflag = true; } } @@ -142,30 +145,32 @@ public class SafePolicyController { } @RequestMapping(value = {"/sp_dictionary/remove_riskType"}, method = {RequestMethod.POST}) - public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) - throws IOException { + public void removeRiskTypeDictionary(HttpServletRequest request, HttpServletResponse response) throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, riskTypeDatas, RiskType.class); } - @RequestMapping(value = {"/get_SafePolicyWarningDataByName"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SafePolicyWarningDataByName"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSafePolicyWarningEntityDataByName(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getDataByEntity(response, safePolicyWarningDatas, "name", SafePolicyWarning.class); } - @RequestMapping(value = {"/get_SafePolicyWarningData"}, method = {RequestMethod.GET}, + @RequestMapping( + value = {"/get_SafePolicyWarningData"}, + method = {RequestMethod.GET}, produces = MediaType.APPLICATION_JSON_VALUE) public void getSafePolicyWarningeEntityData(HttpServletResponse response) { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.getData(response, safePolicyWarningDatas, SafePolicyWarning.class); } - @RequestMapping(value = {"/sp_dictionary/save_safePolicyWarning"}, - method = {RequestMethod.POST}) - public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/save_safePolicyWarning"}, method = {RequestMethod.POST}) + public ModelAndView saveSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); try { boolean fromAPI = utils.isRequestFromAPI(request); @@ -174,25 +179,22 @@ public class SafePolicyController { JsonNode root = mapper.readTree(request.getReader()); SafePolicyWarning safePolicyWarning; if (fromAPI) { - safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), - SafePolicyWarning.class); + safePolicyWarning = mapper.readValue(root.get("dictionaryFields").toString(), SafePolicyWarning.class); } else { - safePolicyWarning = mapper.readValue(root.get("safePolicyWarningData").toString(), - SafePolicyWarning.class); + safePolicyWarning = + mapper.readValue(root.get("safePolicyWarningData").toString(), SafePolicyWarning.class); } - List<Object> duplicateData = commonClassDao.checkDuplicateEntry( - safePolicyWarning.getName(), "name", SafePolicyWarning.class); + List<Object> duplicateData = + commonClassDao.checkDuplicateEntry(safePolicyWarning.getName(), "name", SafePolicyWarning.class); boolean duplicateflag = false; if (!duplicateData.isEmpty()) { SafePolicyWarning data = (SafePolicyWarning) duplicateData.get(0); - if (request.getParameter(operation) != null - && "update".equals(request.getParameter(operation))) { + if (request.getParameter(operation) != null && "update".equals(request.getParameter(operation))) { safePolicyWarning.setId(data.getId()); } else if ((request.getParameter(operation) != null && !"update".equals(request.getParameter(operation))) - || (request.getParameter(operation) == null - && (data.getId() != safePolicyWarning.getId()))) { + || (request.getParameter(operation) == null && (data.getId() != safePolicyWarning.getId()))) { duplicateflag = true; } } @@ -203,8 +205,7 @@ public class SafePolicyController { } else { commonClassDao.update(safePolicyWarning); } - responseString = - mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); + responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class)); } else { responseString = duplicateResponseString; } @@ -219,10 +220,9 @@ public class SafePolicyController { return null; } - @RequestMapping(value = {"/sp_dictionary/remove_SafePolicyWarning"}, - method = {RequestMethod.POST}) - public void removeSafePolicyWarningDictionary(HttpServletRequest request, - HttpServletResponse response) throws IOException { + @RequestMapping(value = {"/sp_dictionary/remove_SafePolicyWarning"}, method = {RequestMethod.POST}) + public void removeSafePolicyWarningDictionary(HttpServletRequest request, HttpServletResponse response) + throws IOException { DictionaryUtils utils = getDictionaryUtilsInstance(); utils.removeData(request, response, safePolicyWarningDatas, SafePolicyWarning.class); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java index bb42fb6aa..7e940a2a1 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/controller/package-info.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -18,5 +18,4 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.pap.xacml.rest.controller; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java index 2688d7d3c..ee5c22f1c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/daoimpl/CommonClassDaoImpl.java @@ -22,7 +22,9 @@ package org.onap.policy.pap.xacml.rest.daoimpl; import java.util.List; import java.util.Map; + import javax.script.SimpleBindings; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Criteria; @@ -51,10 +53,8 @@ public class CommonClassDaoImpl implements CommonClassDao { private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class); - private static SessionFactory sessionFactory; - @Autowired private CommonClassDaoImpl(SessionFactory sessionFactory) { CommonClassDaoImpl.sessionFactory = sessionFactory; @@ -78,14 +78,12 @@ public class CommonClassDaoImpl implements CommonClassDao { try { session.close(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); } } return data; } - @SuppressWarnings({"rawtypes", "unchecked"}) @Override public List<Object> getDataById(Class className, String columnName, String key) { @@ -109,8 +107,7 @@ public class CommonClassDaoImpl implements CommonClassDao { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return data; @@ -131,8 +128,7 @@ public class CommonClassDaoImpl implements CommonClassDao { try { session.close(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e); } } return data; @@ -146,14 +142,12 @@ public class CommonClassDaoImpl implements CommonClassDao { session.persist(entity); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Saving data to Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Saving data to Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } @@ -167,20 +161,17 @@ public class CommonClassDaoImpl implements CommonClassDao { session.delete(entity); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Deleting data from Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Deleting data from Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } } - @Override public void update(Object entity) { Session session = sessionFactory.openSession(); @@ -189,20 +180,17 @@ public class CommonClassDaoImpl implements CommonClassDao { session.update(entity); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Updating data to Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating data to Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } } - @SuppressWarnings({"unchecked", "rawtypes"}) @Override public List<Object> checkDuplicateEntry(String value, String columnName, Class className) { @@ -231,20 +219,18 @@ public class CommonClassDaoImpl implements CommonClassDao { data = cr.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying for Duplicate Entries for Table" + e + className); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying for Duplicate Entries for Table" + + e + className); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return data; } - @SuppressWarnings("unchecked") @Override public List<Object> getDataByQuery(String query, SimpleBindings params) { @@ -263,21 +249,18 @@ public class CommonClassDaoImpl implements CommonClassDao { data = hbquery.list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying Database Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table" + e); throw e; } finally { try { session.close(); } catch (HibernateException e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement", e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement", e1); } } return data; } - @Override public void updateQuery(String query) { Session session = sessionFactory.openSession(); @@ -287,19 +270,16 @@ public class CommonClassDaoImpl implements CommonClassDao { hbquery.executeUpdate(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Updating Database Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating Database Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } } - @SuppressWarnings("rawtypes") @Override public Object getEntityItem(Class className, String columnName, String key) { @@ -320,20 +300,17 @@ public class CommonClassDaoImpl implements CommonClassDao { data = cr.list().get(0); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying Database Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying Database Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return data; } - @SuppressWarnings("unchecked") @Override public List<PolicyRoles> getUserRoles() { @@ -355,20 +332,17 @@ public class CommonClassDaoImpl implements CommonClassDao { rolesData = cr.add(disjunction).list(); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying PolicyRoles Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Querying PolicyRoles Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return rolesData; } - @SuppressWarnings("unchecked") @Override public void updateClAlarms(String clName, String alarms) { @@ -384,14 +358,12 @@ public class CommonClassDaoImpl implements CommonClassDao { session.update(closedloop); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Updating ClosedLoops Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table" + e); } finally { session.close(); } } - @SuppressWarnings("unchecked") @Override public void updateClYaml(String clName, String yaml) { @@ -407,14 +379,12 @@ public class CommonClassDaoImpl implements CommonClassDao { session.update(closedloop); tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Updating ClosedLoops Table" + e); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Updating ClosedLoops Table" + e); } finally { session.close(); } } - @SuppressWarnings("unchecked") @Override public void deleteAll() { @@ -438,8 +408,8 @@ public class CommonClassDaoImpl implements CommonClassDao { tx.commit(); } catch (Exception e) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error while deleting ClosedLoops from the table" + e); + LOGGER.error( + XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error while deleting ClosedLoops from the table" + e); } finally { session.close(); } @@ -447,8 +417,7 @@ public class CommonClassDaoImpl implements CommonClassDao { @SuppressWarnings({"unchecked"}) @Override - public List<Object> checkExistingGroupListforUpdate(String groupListValue, - String groupNameValue) { + public List<Object> checkExistingGroupListforUpdate(String groupListValue, String groupNameValue) { Session session = sessionFactory.openSession(); Transaction tx = session.beginTransaction(); List<Object> data = null; @@ -461,23 +430,20 @@ public class CommonClassDaoImpl implements CommonClassDao { tx.commit(); } catch (Exception e) { LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table" - + e); + + "Error While Querying for Duplicate Entries for GroupPolicyScopeList Table" + e); } finally { try { session.close(); } catch (Exception e1) { - LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW - + "Error While Closing Connection/Statement" + e1); + LOGGER.error(XACMLErrorConstants.ERROR_PROCESS_FLOW + "Error While Closing Connection/Statement" + e1); } } return data; } - @Override - public List<Object> getMultipleDataOnAddingConjunction( - @SuppressWarnings("rawtypes") Class className, String columnName, List<String> data) { + public List<Object> getMultipleDataOnAddingConjunction(@SuppressWarnings("rawtypes") Class className, + String columnName, List<String> data) { return null; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java index f04be861b..cfae68091 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElasticSearchPolicyUpdate.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.elk.client; import com.google.gson.Gson; + import io.searchbox.client.JestClientFactory; import io.searchbox.client.config.HttpClientConfig; import io.searchbox.client.http.JestHttpClient; @@ -28,6 +29,7 @@ import io.searchbox.core.Bulk; import io.searchbox.core.Bulk.Builder; import io.searchbox.core.BulkResult; import io.searchbox.core.Index; + import java.io.ByteArrayInputStream; import java.io.FileInputStream; import java.io.InputStream; @@ -43,6 +45,7 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; @@ -50,13 +53,12 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.utils.PeCryptoUtils; import org.onap.policy.xacml.util.XACMLPolicyScanner; - - /** * This code will deals with parsing the XACML content on reading from * database(PolicyEntity, ConfigurationDataEntity and ActionBodyEntity tables) @@ -126,54 +128,53 @@ public class ElasticSearchPolicyUpdate { String policyEntityQuery = "Select * from PolicyEntity"; result = stmt.executeQuery(policyEntityQuery); - while(result.next()){ + while (result.next()) { StringBuilder policyDataString = new StringBuilder("{"); String scope = result.getString("scope"); String policyName = result.getString("policyName"); - if(policyName != null){ - policyDataString.append("\"policyName\":\""+scope+"."+policyName+"\","); + if (policyName != null) { + policyDataString.append("\"policyName\":\"" + scope + "." + policyName + "\","); } String description = result.getString("description"); - if(description != null){ - policyDataString.append("\"policyDescription\":\""+description+"\","); + if (description != null) { + policyDataString.append("\"policyDescription\":\"" + description + "\","); } Object policyData = result.getString("policydata"); - if(scope != null){ - policyDataString.append("\"scope\":\""+scope+"\","); + if (scope != null) { + policyDataString.append("\"scope\":\"" + scope + "\","); } String actionbodyid = result.getString("actionbodyid"); String configurationdataid = result.getString("configurationdataid"); - String policyWithScopeName = scope + "." + policyName; String _type = null; - if(policyWithScopeName.contains(".Config_")){ + if (policyWithScopeName.contains(".Config_")) { policyDataString.append("\"policyType\":\"Config\","); - if(policyWithScopeName.contains(".Config_Fault_")){ + if (policyWithScopeName.contains(".Config_Fault_")) { _type = "closedloop"; policyDataString.append("\"configPolicyType\":\"ClosedLoop_Fault\","); - }else if(policyWithScopeName.contains(".Config_PM_")){ + } else if (policyWithScopeName.contains(".Config_PM_")) { _type = "closedloop"; policyDataString.append("\"configPolicyType\":\"ClosedLoop_PM\","); - }else{ + } else { _type = "config"; policyDataString.append("\"configPolicyType\":\"Base\","); } - }else if(policyWithScopeName.contains(".Action_")){ + } else if (policyWithScopeName.contains(".Action_")) { _type = "action"; policyDataString.append("\"policyType\":\"Action\","); - }else if(policyWithScopeName.contains(".Decision_")){ + } else if (policyWithScopeName.contains(".Decision_")) { _type = "decision"; policyDataString.append("\"policyType\":\"Decision\","); } - if(!"decision".equals(_type)){ - if(configurationdataid != null){ + if (!"decision".equals(_type)) { + if (configurationdataid != null) { updateConfigData(conn, configurationdataid, policyDataString); } - if(actionbodyid != null){ + if (actionbodyid != null) { updateActionData(conn, actionbodyid, policyDataString); } } @@ -181,72 +182,72 @@ public class ElasticSearchPolicyUpdate { String _id = policyWithScopeName; String dataString = constructPolicyData(policyData, policyDataString); - dataString = dataString.substring(0, dataString.length()-1); + dataString = dataString.substring(0, dataString.length() - 1); dataString = dataString.trim().replace(System.getProperty("line.separator"), "") + "}"; dataString = dataString.replace("null", "\"\""); dataString = dataString.replaceAll("\n", ""); - try{ + try { Gson gson = new Gson(); gson.fromJson(dataString, Object.class); - }catch(Exception e){ + } catch (Exception e) { LOGGER.error(e); continue; } - if("config".equals(_type)){ + if ("config".equals(_type)) { listIndex.add(new Index.Builder(dataString).index("policy").type("config").id(_id).build()); - }else if("closedloop".equals(_type)){ + } else if ("closedloop".equals(_type)) { listIndex.add(new Index.Builder(dataString).index("policy").type("closedloop").id(_id).build()); - }else if("action".equals(_type)){ + } else if ("action".equals(_type)) { listIndex.add(new Index.Builder(dataString).index("policy").type("action").id(_id).build()); - }else if("decision".equals(_type)){ + } else if ("decision".equals(_type)) { listIndex.add(new Index.Builder(dataString).index("policy").type("decision").id(_id).build()); } } result.close(); bulk = new Bulk.Builder(); - for(int i =0; i < listIndex.size(); i++){ + for (int i = 0; i < listIndex.size(); i++) { bulk.addAction(listIndex.get(i)); } BulkResult searchResult = client.execute(bulk.build()); - if(searchResult.isSucceeded()){ + if (searchResult.isSucceeded()) { LOGGER.debug("Success"); - }else{ + } else { LOGGER.error("Failure"); } } catch (Exception e) { - LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade"+e); - }finally{ - if(result != null){ - try { - result.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the resultset"+e); - } + LOGGER.error("Exception Occured while performing database Operation for Elastic Search Policy Upgrade" + e); + } finally { + if (result != null) { + try { + result.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the resultset" + e); } - if(stmt != null){ - try { - stmt.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the statement"+e); - } + } + if (stmt != null) { + try { + stmt.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the statement" + e); } - if(conn != null){ + } + if (conn != null) { try { conn.close(); } catch (Exception e) { - LOGGER.error("Exception Occured while closing the connection"+e); + LOGGER.error("Exception Occured while closing the connection" + e); } } } } - public static String constructPolicyData(Object policyContent, StringBuilder policyDataString){ + public static String constructPolicyData(Object policyContent, StringBuilder policyDataString) { InputStream stream = new ByteArrayInputStream(policyContent.toString().getBytes(StandardCharsets.UTF_8)); Object policyData = XACMLPolicyScanner.readPolicy(stream); - if(policyData instanceof PolicyType){ + if (policyData instanceof PolicyType) { PolicyType policy = (PolicyType) policyData; TargetType target = policy.getTarget(); if (target != null) { @@ -278,19 +279,19 @@ public class ElasticSearchPolicyUpdate { String attributeId = designator.getAttributeId(); // First match in the target is OnapName, so set that value. if ("ONAPName".equals(attributeId)) { - policyDataString.append("\"onapName\":\""+value+"\","); + policyDataString.append("\"onapName\":\"" + value + "\","); } - if ("RiskType".equals(attributeId)){ - policyDataString.append("\"riskType\":\""+value+"\","); + if ("RiskType".equals(attributeId)) { + policyDataString.append("\"riskType\":\"" + value + "\","); } - if ("RiskLevel".equals(attributeId)){ - policyDataString.append("\"riskLevel\":\""+value+"\","); + if ("RiskLevel".equals(attributeId)) { + policyDataString.append("\"riskLevel\":\"" + value + "\","); } - if ("guard".equals(attributeId)){ - policyDataString.append("\"guard\":\""+value+"\","); + if ("guard".equals(attributeId)) { + policyDataString.append("\"guard\":\"" + value + "\","); } - if ("ConfigName".equals(attributeId)){ - policyDataString.append("\"configName\":\""+value+"\","); + if ("ConfigName".equals(attributeId)) { + policyDataString.append("\"configName\":\"" + value + "\","); } } } @@ -303,79 +304,82 @@ public class ElasticSearchPolicyUpdate { return policyDataString.toString(); } - private static void updateConfigData(Connection conn, String configurationdataid, StringBuilder policyDataString) throws Exception { - - PreparedStatement pstmt = null; - ResultSet configResult = null; - try { - String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?"; - pstmt = null; - pstmt = conn.prepareStatement(configEntityQuery); - pstmt.setString(1, configurationdataid); - configResult = pstmt.executeQuery(); - while(configResult.next()){ - String configBody = configResult.getString("configbody"); - String configType = configResult.getString("configtype"); - if(configBody!=null){ - configBody = configBody.replace("null", "\"\""); - configBody= configBody.replace("\"", "\\\""); - policyDataString.append("\"jsonBodyData\":\""+configBody+"\",\"configType\":\""+configType+"\","); - } + private static void updateConfigData(Connection conn, String configurationdataid, StringBuilder policyDataString) + throws Exception { + + PreparedStatement pstmt = null; + ResultSet configResult = null; + try { + String configEntityQuery = "Select * from ConfigurationDataEntity where configurationDataId = ?"; + pstmt = null; + pstmt = conn.prepareStatement(configEntityQuery); + pstmt.setString(1, configurationdataid); + configResult = pstmt.executeQuery(); + while (configResult.next()) { + String configBody = configResult.getString("configbody"); + String configType = configResult.getString("configtype"); + if (configBody != null) { + configBody = configBody.replace("null", "\"\""); + configBody = configBody.replace("\"", "\\\""); + policyDataString + .append("\"jsonBodyData\":\"" + configBody + "\",\"configType\":\"" + configType + "\","); } - } catch(Exception e) { - LOGGER.error("Exception Occured while updating configData"+e); - throw(e); - } finally { - if(configResult != null){ - try { - configResult.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the ResultSet"+e); - } + } + } catch (Exception e) { + LOGGER.error("Exception Occured while updating configData" + e); + throw (e); + } finally { + if (configResult != null) { + try { + configResult.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the ResultSet" + e); } - if(pstmt != null){ - try { - pstmt.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the PreparedStatement"+e); - } + } + if (pstmt != null) { + try { + pstmt.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the PreparedStatement" + e); } - } + } + } } - private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) throws Exception { - - PreparedStatement pstmt = null; - ResultSet actionResult = null; - try { - String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?"; - pstmt = conn.prepareStatement(actionEntityQuery); - pstmt.setString(1, actionbodyid); - actionResult = pstmt.executeQuery(); - while(actionResult.next()){ - String actionBody = actionResult.getString("actionbody"); - actionBody = actionBody.replace("null", "\"\""); - actionBody = actionBody.replace("\"", "\\\""); - policyDataString.append("\"jsonBodyData\":\""+actionBody+"\","); - } - } catch(Exception e) { - LOGGER.error("Exception Occured while updating actionData"+e); - throw(e); - } finally { - if(actionResult != null){ - try { - actionResult.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the ResultSet"+e); - } + private static void updateActionData(Connection conn, String actionbodyid, StringBuilder policyDataString) + throws Exception { + + PreparedStatement pstmt = null; + ResultSet actionResult = null; + try { + String actionEntityQuery = "Select * from ActionBodyEntity where actionBodyId = ?"; + pstmt = conn.prepareStatement(actionEntityQuery); + pstmt.setString(1, actionbodyid); + actionResult = pstmt.executeQuery(); + while (actionResult.next()) { + String actionBody = actionResult.getString("actionbody"); + actionBody = actionBody.replace("null", "\"\""); + actionBody = actionBody.replace("\"", "\\\""); + policyDataString.append("\"jsonBodyData\":\"" + actionBody + "\","); + } + } catch (Exception e) { + LOGGER.error("Exception Occured while updating actionData" + e); + throw (e); + } finally { + if (actionResult != null) { + try { + actionResult.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the ResultSet" + e); } - if(pstmt != null){ - try { - pstmt.close(); - } catch (Exception e) { - LOGGER.error("Exception Occured while closing the PreparedStatement"+e); - } + } + if (pstmt != null) { + try { + pstmt.close(); + } catch (Exception e) { + LOGGER.error("Exception Occured while closing the PreparedStatement" + e); } - } + } + } } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java index d64b71763..d3f7f4dea 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnector.java @@ -20,9 +20,10 @@ package org.onap.policy.pap.xacml.rest.elk.client; - import io.searchbox.client.JestResult; + import java.util.Map; + import org.onap.policy.rest.adapter.PolicyRestAdapter; public interface ElkConnector { @@ -44,8 +45,7 @@ public interface ElkConnector { public boolean delete(PolicyRestAdapter policyData) throws IllegalStateException; - public JestResult search(PolicyIndexType type, String text) - throws IllegalStateException, IllegalArgumentException; + public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException; public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) throws IllegalStateException, IllegalArgumentException; @@ -54,8 +54,7 @@ public interface ElkConnector { public ElkConnector singleton = new ElkConnectorImpl(); - public static PolicyIndexType toPolicyIndexType(String policyName) - throws IllegalArgumentException { + public static PolicyIndexType toPolicyIndexType(String policyName) throws IllegalArgumentException { if (policyName == null) throw new IllegalArgumentException("Unsupported NULL policy name conversion"); @@ -76,8 +75,7 @@ public interface ElkConnector { } else if (policyName.startsWith("Config")) { return PolicyIndexType.config; } else { - throw new IllegalArgumentException( - "Unsupported policy name conversion to index: " + policyName); + throw new IllegalArgumentException("Unsupported policy name conversion to index: " + policyName); } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java index 6bbe033a3..4d84526a5 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/ElkConnectorImpl.java @@ -32,9 +32,11 @@ import io.searchbox.core.Search.Builder; import io.searchbox.indices.IndicesExists; import io.searchbox.indices.type.TypeExist; import io.searchbox.params.Parameters; + import java.io.IOException; import java.util.Map; import java.util.Map.Entry; + import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.QueryStringQueryBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder; @@ -56,8 +58,7 @@ public class ElkConnectorImpl implements ElkConnector { if (LOGGER.isDebugEnabled()) { LOGGER.debug("ENTER: -"); } - HttpClientConfig jestClientConfig = - new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); + HttpClientConfig jestClientConfig = new HttpClientConfig.Builder(ELK_URL).multiThreaded(true).build(); jestFactory.setHttpClientConfig(jestClientConfig); jestClient = jestFactory.getObject(); } @@ -68,8 +69,7 @@ public class ElkConnectorImpl implements ElkConnector { } try { - Action<JestResult> typeQuery = - new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); + Action<JestResult> typeQuery = new TypeExist.Builder(ELK_INDEX_POLICY).addType(type.toString()).build(); JestResult result = jestClient.execute(typeQuery); if (LOGGER.isInfoEnabled()) { @@ -80,9 +80,7 @@ public class ElkConnectorImpl implements ElkConnector { } return result.isSucceeded(); } catch (IOException e) { - LOGGER.warn( - "Error checking type existance of " + type.toString() + ": " + e.getMessage(), - e); + LOGGER.warn("Error checking type existance of " + type.toString() + ": " + e.getMessage(), e); throw e; } } @@ -100,9 +98,7 @@ public class ElkConnectorImpl implements ElkConnector { } return result.isSucceeded(); } catch (IOException e) { - LOGGER.warn( - "Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), - e); + LOGGER.warn("Error checking index existance of " + ELK_INDEX_POLICY + ": " + e.getMessage(), e); throw e; } } @@ -112,8 +108,7 @@ public class ElkConnectorImpl implements ElkConnector { } @Override - public JestResult search(PolicyIndexType type, String text) - throws IllegalStateException, IllegalArgumentException { + public JestResult search(PolicyIndexType type, String text) throws IllegalStateException, IllegalArgumentException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("ENTER: " + text); } @@ -129,9 +124,8 @@ public class ElkConnectorImpl implements ElkConnector { QueryStringQueryBuilder mQ = QueryBuilders.queryStringQuery("*" + text + "*"); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(mQ); - Builder searchBuilder = - new Search.Builder(searchSourceBuilder.toString()).addIndex(ELK_INDEX_POLICY) - .setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); + Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()).addIndex(ELK_INDEX_POLICY) + .setParameter(Parameters.SIZE, ElkConnectorImpl.QUERY_MAXRECORDS); if (type == null || type == PolicyIndexType.all) { for (PolicyIndexType pT : PolicyIndexType.values()) { @@ -148,24 +142,21 @@ public class ElkConnectorImpl implements ElkConnector { try { result = jestClient.execute(search); } catch (IOException ioe) { - LOGGER.warn( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), - ioe); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), ioe); throw new IllegalStateException(ioe); } if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) { - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " - + result.getPathToResult() + ":" + System.lineSeparator() - + result.getJsonString()); + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + result.getPathToResult() + ":" + + System.lineSeparator() + result.getJsonString()); } } else { /* Unsuccessful search */ if (LOGGER.isWarnEnabled()) { - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() - + ": " + search.getURI() + ":" + result.getPathToResult() + ":" - + result.getJsonString() + ":" + result.getErrorMessage()); + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + ": " + + search.getURI() + ":" + result.getPathToResult() + ":" + result.getJsonString() + ":" + + result.getErrorMessage()); } String errorMessage = result.getErrorMessage(); @@ -173,24 +164,19 @@ public class ElkConnectorImpl implements ElkConnector { String xMessage; if (errorMessage.contains("TokenMgrError")) { int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("QueryParsingException")) { int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("JsonParseException")) { int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("Parse Failure")) { int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("SearchParseException")) { int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else { xMessage = result.getErrorMessage(); } @@ -201,7 +187,6 @@ public class ElkConnectorImpl implements ElkConnector { return result; } - @Override public JestResult search(PolicyIndexType type, String text, Map<String, String> filter_s) throws IllegalStateException, IllegalArgumentException { @@ -218,8 +203,8 @@ public class ElkConnectorImpl implements ElkConnector { } String matches_s = ""; - matches_s = "{\n" + " \"size\" : " + ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" - + " \"query\": {\n" + " \"bool\" : {\n" + " \"must\" : ["; + matches_s = "{\n" + " \"size\" : " + ElkConnectorImpl.QUERY_MAXRECORDS + ",\n" + " \"query\": {\n" + + " \"bool\" : {\n" + " \"must\" : ["; String match_params = ""; boolean first = true; @@ -230,8 +215,7 @@ public class ElkConnectorImpl implements ElkConnector { match_params = "\"match\" : {\"" + key + "\" : \"" + value + "\" }},"; first = false; } else { - match_params = - match_params + "{\"match\" : { \"" + key + "\" : \"" + value + "\" } },"; + match_params = match_params + "{\"match\" : { \"" + key + "\" : \"" + value + "\" } },"; } } if (match_params.endsWith(",")) { @@ -271,24 +255,21 @@ public class ElkConnectorImpl implements ElkConnector { try { result = jestClient.execute(search); } catch (IOException ioe) { - LOGGER.warn( - XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), - ioe); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ":" + search + ": " + ioe.getMessage(), ioe); throw new IllegalStateException(ioe); } if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) { - LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " - + result.getPathToResult() + ":" + System.lineSeparator() - + result.getJsonString()); + LOGGER.info("OK:" + result.getResponseCode() + ":" + search + ": " + result.getPathToResult() + ":" + + System.lineSeparator() + result.getJsonString()); } } else { /* Unsuccessful search */ if (LOGGER.isWarnEnabled()) { - LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() - + ": " + search.getURI() + ":" + result.getPathToResult() + ":" - + result.getJsonString() + ":" + result.getErrorMessage()); + LOGGER.warn(XACMLErrorConstants.ERROR_PROCESS_FLOW + ":" + result.getResponseCode() + ": " + + search.getURI() + ":" + result.getPathToResult() + ":" + result.getJsonString() + ":" + + result.getErrorMessage()); } String errorMessage = result.getErrorMessage(); @@ -296,24 +277,19 @@ public class ElkConnectorImpl implements ElkConnector { String xMessage = errorMessage; if (errorMessage.contains("TokenMgrError")) { int indexError = errorMessage.lastIndexOf("TokenMgrError"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("QueryParsingException")) { int indexError = errorMessage.lastIndexOf("QueryParsingException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("JsonParseException")) { int indexError = errorMessage.lastIndexOf("JsonParseException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("Parse Failure")) { int indexError = errorMessage.lastIndexOf("Parse Failure"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else if (errorMessage.contains("SearchParseException")) { int indexError = errorMessage.lastIndexOf("SearchParseException"); - xMessage = "Invalid Search Expression. Details: " - + errorMessage.substring(indexError); + xMessage = "Invalid Search Expression. Details: " + errorMessage.substring(indexError); } else { xMessage = result.getErrorMessage(); } @@ -347,22 +323,20 @@ public class ElkConnectorImpl implements ElkConnector { } PolicyElasticData elasticData = new PolicyElasticData(policyData); JSONObject jsonObj = new JSONObject(elasticData); - Index elkPut = new Index.Builder(jsonObj.toString()).index(ELK_INDEX_POLICY) - .type(indexType.name()).id(elasticData.getPolicyName()).refresh(true).build(); + Index elkPut = new Index.Builder(jsonObj.toString()).index(ELK_INDEX_POLICY).type(indexType.name()) + .id(elasticData.getPolicyName()).refresh(true).build(); JestResult result = jestClient.execute(elkPut); if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) - LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + "success=" - + result.isSucceeded() + "[" + result.getResponseCode() + ":" - + result.getPathToResult() + "]" + System.lineSeparator() + LOGGER.info("ElkConnector: OK: PUT operation of " + "->" + ": " + "success=" + result.isSucceeded() + + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); } else { if (LOGGER.isWarnEnabled()) - LOGGER.warn("ElkConnector: FAILURE: PUT operation of " + "->" + ": " + "success=" - + result.isSucceeded() + "[" + result.getResponseCode() + ":" - + result.getPathToResult() + "]" + System.lineSeparator() + LOGGER.warn("ElkConnector: FAILURE: PUT operation of " + "->" + ": " + "success=" + result.isSucceeded() + + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); } @@ -387,31 +361,29 @@ public class ElkConnectorImpl implements ElkConnector { String[] splitPolicyName = policyName.split(":"); indexType = ElkConnector.toPolicyIndexType(splitPolicyName[1]); if (!isType(indexType)) { - throw new IllegalStateException("ELK: Index: " + ELK_INDEX_POLICY + " Type: " - + indexType + " is not configured"); + throw new IllegalStateException( + "ELK: Index: " + ELK_INDEX_POLICY + " Type: " + indexType + " is not configured"); } PolicyElasticData elasticData = new PolicyElasticData(policyData); - Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()) - .index(ELK_INDEX_POLICY).type(indexType.name()).build(); + Delete deleteRequest = new Delete.Builder(elasticData.getPolicyName()).index(ELK_INDEX_POLICY) + .type(indexType.name()).build(); result = jestClient.execute(deleteRequest); } catch (IllegalArgumentException | IOException e) { - LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + indexType + ": null" - + ":" + policyData.getNewFileName() + ": " + e.getMessage(), e); + LOGGER.warn(XACMLErrorConstants.ERROR_SYSTEM_ERROR + ": delete:" + indexType + ": null" + ":" + + policyData.getNewFileName() + ": " + e.getMessage(), e); throw new IllegalStateException(e); } if (result.isSucceeded()) { if (LOGGER.isInfoEnabled()) - LOGGER.info("OK: DELETE operation of " + indexType + ":" - + policyData.getNewFileName() + ": " + "success=" + result.isSucceeded() - + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" - + System.lineSeparator() + result.getJsonString()); + LOGGER.info("OK: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); } else { if (LOGGER.isWarnEnabled()) - LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" - + policyData.getNewFileName() + ": " + "success=" + result.isSucceeded() - + "[" + result.getResponseCode() + ":" + result.getPathToResult() + "]" - + System.lineSeparator() + result.getJsonString()); + LOGGER.warn("FAILURE: DELETE operation of " + indexType + ":" + policyData.getNewFileName() + ": " + + "success=" + result.isSucceeded() + "[" + result.getResponseCode() + ":" + + result.getPathToResult() + "]" + System.lineSeparator() + result.getJsonString()); } return result.isSucceeded(); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java index 2b0c94bf3..cd3fc4f0c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/Pair.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,17 +17,31 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; -public class Pair<L,R> { +public class Pair<L, R> { private L left; private R right; - public Pair(L l, R r){ + + public Pair(L l, R r) { + this.left = l; + this.right = r; + } + + public L left() { + return left; + } + + public R right() { + return right; + } + + public void left(L l) { this.left = l; + } + + public void right(R r) { this.right = r; } - public L left(){ return left; } - public R right(){ return right; } - public void left(L l){ this.left = l; } - public void right(R r){ this.right = r; } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java index 988640ca6..70964c487 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticData.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; import java.util.ArrayList; @@ -46,14 +47,14 @@ public class PolicyElasticData { private Map<?, ?> description; private Map<?, ?> attributeFields; - //Safe Policy + // Safe Policy private String policyScope; private String providerComboBox; private String riskType; private String riskLevel; private String guard; private String ttlDate; - private Map<String,String> matching; + private Map<String, String> matching; private List<Object> triggerSignatures; private List<Object> symptomSignatures; @@ -62,39 +63,39 @@ public class PolicyElasticData { public String gocServerScope; private String supressionType; - //MicroSerice + // MicroSerice private String serviceType; private String uuid; private String location; private String priority; private String msLocation; - //BRMS Policies + // BRMS Policies private String ruleName; - private Map<String,String> brmsParamBody; + private Map<String, String> brmsParamBody; private String brmsController; private List<String> brmsDependency; - private LinkedHashMap<?, ?> ruleData; - private LinkedHashMap<?,?> ruleListData; - private Map<String,String> drlRuleAndUIParams; + private LinkedHashMap<?, ?> ruleData; + private LinkedHashMap<?, ?> ruleListData; + private Map<String, String> drlRuleAndUIParams; - //ClosedLoop + // ClosedLoop private String clearTimeOut; private String trapMaxAge; private String verificationclearTimeOut; - public Map<String , String> dynamicLayoutMap; + public Map<String, String> dynamicLayoutMap; - //FireWall + // FireWall private String fwPolicyType; private List<Object> fwattributes; private String parentForChild; private String securityZone; - //Action & Decision + // Action & Decision private String ruleCombiningAlgId; - private Map<String,String> dynamicFieldConfigAttributes; - private Map<String,String> dynamicSettingsMap; - private Map<String,String> dropDownMap; + private Map<String, String> dynamicFieldConfigAttributes; + private Map<String, String> dynamicSettingsMap; + private Map<String, String> dropDownMap; private String actionPerformer; private String actionAttribute; private List<String> dynamicRuleAlgorithmLabels; @@ -117,15 +118,15 @@ public class PolicyElasticData { this.policyType = policyData.getPolicyType(); this.configPolicyType = policyData.getConfigPolicyType(); this.configBodyData = policyData.getConfigBodyData(); - this.policyName = policyData.getNewFileName(); - this.policyDescription = policyData.getPolicyDescription(); + this.policyName = policyData.getNewFileName(); + this.policyDescription = policyData.getPolicyDescription(); this.onapName = policyData.getOnapName(); this.configName = policyData.getConfigName(); this.configType = policyData.getConfigType(); this.jsonBody = policyData.getJsonBody(); - if(configPolicyType.startsWith("ClosedLoop")){ + if (configPolicyType.startsWith("ClosedLoop")) { this.jsonBodyData = jsonBody; - }else{ + } else { this.jsonBodyData = policyData.getJsonBodyData(); } @@ -134,12 +135,12 @@ public class PolicyElasticData { this.description = policyData.getDescription(); this.attributeFields = policyData.getAttributeFields(); - //Safe Policy + // Safe Policy this.policyScope = policyData.getPolicyScope(); this.providerComboBox = policyData.getProviderComboBox(); this.riskType = policyData.getRiskType(); this.riskLevel = policyData.getRiskLevel(); - this.guard = policyData.getGuard(); + this.guard = policyData.getGuard(); this.ttlDate = policyData.getTtlDate(); this.matching = policyData.getMatching(); @@ -150,14 +151,14 @@ public class PolicyElasticData { this.gocServerScope = policyData.getGocServerScope(); this.supressionType = policyData.getSupressionType(); - //MicroSerice + // MicroSerice this.serviceType = policyData.getServiceType(); this.uuid = policyData.getUuid(); this.location = policyData.getLocation(); this.priority = policyData.getPriority(); this.msLocation = policyData.getMsLocation(); - //BRMS Policies + // BRMS Policies this.ruleName = policyData.getRuleName(); this.brmsParamBody = policyData.getBrmsParamBody(); this.brmsController = policyData.getBrmsController(); @@ -166,19 +167,19 @@ public class PolicyElasticData { this.ruleListData = policyData.getRuleListData(); this.drlRuleAndUIParams = policyData.getDrlRuleAndUIParams(); - //ClosedLoop + // ClosedLoop this.clearTimeOut = policyData.getClearTimeOut(); this.trapMaxAge = policyData.getTrapMaxAge(); this.verificationclearTimeOut = policyData.getVerificationclearTimeOut(); this.dynamicLayoutMap = policyData.getDynamicLayoutMap(); - //FireWall + // FireWall this.fwPolicyType = policyData.getFwPolicyType(); this.fwattributes = policyData.getFwattributes(); this.parentForChild = policyData.getParentForChild(); this.securityZone = policyData.getSecurityZone(); - //Action & Decision + // Action & Decision this.ruleCombiningAlgId = policyData.getRuleCombiningAlgId(); this.dynamicFieldConfigAttributes = policyData.getDynamicFieldConfigAttributes(); this.dynamicSettingsMap = policyData.getDynamicSettingsMap(); @@ -204,21 +205,27 @@ public class PolicyElasticData { public String getScope() { return scope; } + public void setScope(String scope) { this.scope = scope; } + public String getPolicyType() { return policyType; } + public void setPolicyType(String policyType) { this.policyType = policyType; } + public String getConfigPolicyType() { return configPolicyType; } + public void setConfigPolicyType(String configPolicyType) { this.configPolicyType = configPolicyType; } + public String getConfigBodyData() { return configBodyData; } @@ -226,42 +233,55 @@ public class PolicyElasticData { public void setConfigBodyData(String configBodyData) { this.configBodyData = configBodyData; } + public String getPolicyName() { return policyName; } + public void setPolicyName(String policyName) { this.policyName = policyName; } + public String getPolicyDescription() { return policyDescription; } + public void setPolicyDescription(String policyDescription) { this.policyDescription = policyDescription; } + public String getOnapName() { return onapName; } + public void setOnapName(String onapName) { this.onapName = onapName; } + public String getConfigName() { return configName; } + public void setConfigName(String configName) { this.configName = configName; } + public String getConfigType() { return configType; } + public void setConfigType(String configType) { this.configType = configType; } + public String getJsonBody() { return jsonBody; } + public void setJsonBody(String jsonBody) { this.jsonBody = jsonBody; } + public Map<?, ?> getServiceTypePolicyName() { return serviceTypePolicyName; } @@ -293,318 +313,423 @@ public class PolicyElasticData { public void setAttributeFields(LinkedHashMap<?, ?> attributeFields) { this.attributeFields = attributeFields; } + public String getPolicyScope() { return policyScope; } + public void setPolicyScope(String policyScope) { this.policyScope = policyScope; } + public String getProviderComboBox() { return providerComboBox; } + public void setProviderComboBox(String providerComboBox) { this.providerComboBox = providerComboBox; } + public String getRiskType() { return riskType; } + public void setRiskType(String riskType) { this.riskType = riskType; } + public String getRiskLevel() { return riskLevel; } + public void setRiskLevel(String riskLevel) { this.riskLevel = riskLevel; } + public String getGuard() { return guard; } + public void setGuard(String guard) { this.guard = guard; } + public String getTtlDate() { return ttlDate; } + public void setTtlDate(String ttlDate) { this.ttlDate = ttlDate; } + public Map<String, String> getMatching() { return matching; } + public void setMatching(Map<String, String> matching) { this.matching = matching; } + public List<Object> getTriggerSignatures() { return triggerSignatures; } + public void setTriggerSignatures(ArrayList<Object> triggerSignatures) { this.triggerSignatures = triggerSignatures; } + public List<Object> getSymptomSignatures() { return symptomSignatures; } + public void setSymptomSignatures(ArrayList<Object> symptomSignatures) { this.symptomSignatures = symptomSignatures; } + public String getLogicalConnector() { return logicalConnector; } + public void setLogicalConnector(String logicalConnector) { this.logicalConnector = logicalConnector; } + public String getPolicyStatus() { return policyStatus; } + public void setPolicyStatus(String policyStatus) { this.policyStatus = policyStatus; } + public String getGocServerScope() { return gocServerScope; } + public void setGocServerScope(String gocServerScope) { this.gocServerScope = gocServerScope; } + public String getSupressionType() { return supressionType; } + public void setSupressionType(String supressionType) { this.supressionType = supressionType; } + public String getServiceType() { return serviceType; } + public void setServiceType(String serviceType) { this.serviceType = serviceType; } + public String getUuid() { return uuid; } + public void setUuid(String uuid) { this.uuid = uuid; } + public String getLocation() { return location; } + public void setLocation(String location) { this.location = location; } + public String getPriority() { return priority; } + public void setPriority(String priority) { this.priority = priority; } + public String getMsLocation() { return msLocation; } + public void setMsLocation(String msLocation) { this.msLocation = msLocation; } + public String getRuleName() { return ruleName; } + public void setRuleName(String ruleName) { this.ruleName = ruleName; } + public Map<String, String> getBrmsParamBody() { return brmsParamBody; } + public void setBrmsParamBody(Map<String, String> brmsParamBody) { this.brmsParamBody = brmsParamBody; } + public String getBrmsController() { return brmsController; } + public void setBrmsController(String brmsController) { this.brmsController = brmsController; } + public List<String> getBrmsDependency() { return brmsDependency; } + public void setBrmsDependency(List<String> brmsDependency) { this.brmsDependency = brmsDependency; } + public Map<?, ?> getRuleData() { return ruleData; } + public void setRuleData(LinkedHashMap<?, ?> ruleData) { this.ruleData = ruleData; } + public Map<?, ?> getRuleListData() { return ruleListData; } + public void setRuleListData(LinkedHashMap<?, ?> ruleListData) { this.ruleListData = ruleListData; } + public Map<String, String> getDrlRuleAndUIParams() { return drlRuleAndUIParams; } + public void setDrlRuleAndUIParams(Map<String, String> drlRuleAndUIParams) { this.drlRuleAndUIParams = drlRuleAndUIParams; } + public String getClearTimeOut() { return clearTimeOut; } + public void setClearTimeOut(String clearTimeOut) { this.clearTimeOut = clearTimeOut; } + public String getTrapMaxAge() { return trapMaxAge; } + public void setTrapMaxAge(String trapMaxAge) { this.trapMaxAge = trapMaxAge; } + public String getVerificationclearTimeOut() { return verificationclearTimeOut; } + public void setVerificationclearTimeOut(String verificationclearTimeOut) { this.verificationclearTimeOut = verificationclearTimeOut; } + public Map<String, String> getDynamicLayoutMap() { return dynamicLayoutMap; } + public void setDynamicLayoutMap(Map<String, String> dynamicLayoutMap) { this.dynamicLayoutMap = dynamicLayoutMap; } + public String getFwPolicyType() { return fwPolicyType; } + public void setFwPolicyType(String fwPolicyType) { this.fwPolicyType = fwPolicyType; } + public List<Object> getFwattributes() { return fwattributes; } + public void setFwattributes(ArrayList<Object> fwattributes) { this.fwattributes = fwattributes; } + public String getParentForChild() { return parentForChild; } + public void setParentForChild(String parentForChild) { this.parentForChild = parentForChild; } + public String getSecurityZone() { return securityZone; } + public void setSecurityZone(String securityZone) { this.securityZone = securityZone; } + public String getRuleCombiningAlgId() { return ruleCombiningAlgId; } + public void setRuleCombiningAlgId(String ruleCombiningAlgId) { this.ruleCombiningAlgId = ruleCombiningAlgId; } + public Map<String, String> getDynamicFieldConfigAttributes() { return dynamicFieldConfigAttributes; } + public void setDynamicFieldConfigAttributes(Map<String, String> dynamicFieldConfigAttributes) { this.dynamicFieldConfigAttributes = dynamicFieldConfigAttributes; } + public Map<String, String> getDynamicSettingsMap() { return dynamicSettingsMap; } + public void setDynamicSettingsMap(Map<String, String> dynamicSettingsMap) { this.dynamicSettingsMap = dynamicSettingsMap; } + public Map<String, String> getDropDownMap() { return dropDownMap; } + public void setDropDownMap(Map<String, String> dropDownMap) { this.dropDownMap = dropDownMap; } + public String getActionPerformer() { return actionPerformer; } + public void setActionPerformer(String actionPerformer) { this.actionPerformer = actionPerformer; } + public String getActionAttribute() { return actionAttribute; } + public void setActionAttribute(String actionAttribute) { this.actionAttribute = actionAttribute; } + public List<String> getDynamicRuleAlgorithmLabels() { return dynamicRuleAlgorithmLabels; } + public void setDynamicRuleAlgorithmLabels(List<String> dynamicRuleAlgorithmLabels) { this.dynamicRuleAlgorithmLabels = dynamicRuleAlgorithmLabels; } + public List<String> getDynamicRuleAlgorithmCombo() { return dynamicRuleAlgorithmCombo; } + public void setDynamicRuleAlgorithmCombo(List<String> dynamicRuleAlgorithmCombo) { this.dynamicRuleAlgorithmCombo = dynamicRuleAlgorithmCombo; } + public List<String> getDynamicRuleAlgorithmField1() { return dynamicRuleAlgorithmField1; } + public void setDynamicRuleAlgorithmField1(List<String> dynamicRuleAlgorithmField1) { this.dynamicRuleAlgorithmField1 = dynamicRuleAlgorithmField1; } + public List<String> getDynamicRuleAlgorithmField2() { return dynamicRuleAlgorithmField2; } + public void setDynamicRuleAlgorithmField2(List<String> dynamicRuleAlgorithmField2) { this.dynamicRuleAlgorithmField2 = dynamicRuleAlgorithmField2; } + public List<Object> getDynamicVariableList() { return dynamicVariableList; } + public void setDynamicVariableList(List<Object> dynamicVariableList) { this.dynamicVariableList = dynamicVariableList; } + public List<String> getDataTypeList() { return dataTypeList; } + public void setDataTypeList(List<String> dataTypeList) { this.dataTypeList = dataTypeList; } + public String getActionAttributeValue() { return actionAttributeValue; } + public void setActionAttributeValue(String actionAttributeValue) { this.actionAttributeValue = actionAttributeValue; } + public String getRuleProvider() { return ruleProvider; } + public void setRuleProvider(String ruleProvider) { this.ruleProvider = ruleProvider; } + public String getActionBody() { return actionBody; } + public void setActionBody(String actionBody) { this.actionBody = actionBody; } + public String getActionDictHeader() { return actionDictHeader; } + public void setActionDictHeader(String actionDictHeader) { this.actionDictHeader = actionDictHeader; } + public String getActionDictType() { return actionDictType; } + public void setActionDictType(String actionDictType) { this.actionDictType = actionDictType; } + public String getActionDictUrl() { return actionDictUrl; } + public void setActionDictUrl(String actionDictUrl) { this.actionDictUrl = actionDictUrl; } + public String getActionDictMethod() { return actionDictMethod; } + public void setActionDictMethod(String actionDictMethod) { this.actionDictMethod = actionDictMethod; } + public YAMLParams getYamlparams() { return yamlparams; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java index 50965bd2b..36ecf83b8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyElasticSearchController.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -17,8 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonArray; + +import io.searchbox.client.JestResult; import java.io.IOException; import java.io.PrintWriter; @@ -66,24 +73,14 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.gson.JsonArray; - -import io.searchbox.client.JestResult; - @Controller @RequestMapping({"/"}) -public class PolicyElasticSearchController{ +public class PolicyElasticSearchController { private static final Logger LOGGER = FlexLogger.getLogger(PolicyElasticSearchController.class); - enum Mode{ - attribute, onapName, actionPolicy, brmsParam, pepOptions, - clSite, clService, clVarbind, clVnf, clVSCL, decision, - fwTerm, msDCAEUUID, msConfigName, msLocation, msModels, - psGroupPolicy, safeRisk, safePolicyWarning + enum Mode { + attribute, onapName, actionPolicy, brmsParam, pepOptions, clSite, clService, clVarbind, clVnf, clVSCL, decision, fwTerm, msDCAEUUID, msConfigName, msLocation, msModels, psGroupPolicy, safeRisk, safePolicyWarning } protected static final HashMap<String, String> name2jsonPath = new HashMap<String, String>() { @@ -108,7 +105,7 @@ public class PolicyElasticSearchController{ } public ElkConnector.PolicyIndexType toPolicyIndexType(String type) throws IllegalArgumentException { - if (type == null || type.isEmpty()){ + if (type == null || type.isEmpty()) { return PolicyIndexType.all; } return PolicyIndexType.valueOf(type); @@ -154,11 +151,10 @@ public class PolicyElasticSearchController{ return success; } - - @RequestMapping(value="/searchPolicy", method= RequestMethod.POST) + @RequestMapping(value = "/searchPolicy", method = RequestMethod.POST) public void searchPolicy(HttpServletRequest request, HttpServletResponse response) { - try{ - String message=""; + try { + String message = ""; boolean result = false; boolean policyResult = false; boolean validationCheck = true; @@ -168,16 +164,16 @@ public class PolicyElasticSearchController{ PolicyElasticSearchController controller = new PolicyElasticSearchController(); Map<String, String> searchKeyValue = new HashMap<>(); List<String> policyList = new ArrayList<>(); - if(request.getParameter("policyName") != null){ + if (request.getParameter("policyName") != null) { String policyName = request.getParameter("policyName"); policyData.setNewFileName(policyName); - if("delete".equalsIgnoreCase(request.getParameter(action))){ + if ("delete".equalsIgnoreCase(request.getParameter(action))) { result = controller.deleteElk(policyData); - }else{ + } else { result = controller.updateElk(policyData); } } - if("search".equalsIgnoreCase(request.getParameter(action))){ + if ("search".equalsIgnoreCase(request.getParameter(action))) { try { JsonNode root = mapper.readTree(request.getReader()); SearchData searchData = mapper.readValue(root.get("searchdata").toString(), SearchData.class); @@ -186,111 +182,117 @@ public class PolicyElasticSearchController{ String searchText = searchData.getQuery(); String descriptivevalue = searchData.getDescriptiveScope(); - if(descriptivevalue != null){ - DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao.getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue); - if(dsSearch != null){ - String[] descriptiveList = dsSearch.getSearch().split("AND"); - for(String keyValue : descriptiveList){ + if (descriptivevalue != null) { + DescriptiveScope dsSearch = (DescriptiveScope) commonClassDao + .getEntityItem(DescriptiveScope.class, "descriptiveScopeName", descriptivevalue); + if (dsSearch != null) { + String[] descriptiveList = dsSearch.getSearch().split("AND"); + for (String keyValue : descriptiveList) { String[] entry = keyValue.split(":"); - if(searchData.getPolicyType() != null && "closedLoop".equals(searchData.getPolicyType())){ - if(!PolicyUtils.policySpecialCharValidator(entry[1]).contains(success)){ - message = "The Descriptive Scope Dictionary value contains space and it is invalid for Search : "+entry[1]; + if (searchData.getPolicyType() != null + && "closedLoop".equals(searchData.getPolicyType())) { + if (!PolicyUtils.policySpecialCharValidator(entry[1]).contains(success)) { + message = + "The Descriptive Scope Dictionary value contains space and it is invalid for Search : " + + entry[1]; validationCheck = false; } - searchKeyValue.put(jsonBodyData, "*" +entry[1] +"*"); - }else{ + searchKeyValue.put(jsonBodyData, "*" + entry[1] + "*"); + } else { searchText = entry[1]; } } } } - if(!PolicyUtils.policySpecialCharValidator(searchText).contains(success)){ - message = "The Search value contains space and it is invalid for Search : "+searchText; + if (!PolicyUtils.policySpecialCharValidator(searchText).contains(success)) { + message = "The Search value contains space and it is invalid for Search : " + searchText; validationCheck = false; } - if(searchData.getClosedLooppolicyType() != null){ + if (searchData.getClosedLooppolicyType() != null) { String closedLoopType; - if("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())){ - closedLoopType = "ClosedLoop_Fault"; - }else{ - closedLoopType = "ClosedLoop_PM"; + if ("Config_Fault".equalsIgnoreCase(searchData.getClosedLooppolicyType())) { + closedLoopType = "ClosedLoop_Fault"; + } else { + closedLoopType = "ClosedLoop_PM"; } searchKeyValue.put("configPolicyType", closedLoopType); } - if(searchData.getOnapName() != null){ + if (searchData.getOnapName() != null) { searchKeyValue.put("onapName", searchData.getOnapName()); } - if(searchData.getD2Service() != null){ + if (searchData.getD2Service() != null) { String d2Service = searchData.getD2Service().trim(); - if("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)){ + if ("Hosted Voice (Trinity)".equalsIgnoreCase(d2Service)) { d2Service = "trinity"; - }else if("vUSP".equalsIgnoreCase(d2Service)){ + } else if ("vUSP".equalsIgnoreCase(d2Service)) { d2Service = "vUSP"; - }else if("MCR".equalsIgnoreCase(d2Service)){ + } else if ("MCR".equalsIgnoreCase(d2Service)) { d2Service = "mcr"; - }else if("Gamma".equalsIgnoreCase(d2Service)){ + } else if ("Gamma".equalsIgnoreCase(d2Service)) { d2Service = "gamma"; - }else if("vDNS".equalsIgnoreCase(d2Service)){ + } else if ("vDNS".equalsIgnoreCase(d2Service)) { d2Service = "vDNS"; } - searchKeyValue.put("jsonBodyData."+d2Service+"", "true"); + searchKeyValue.put("jsonBodyData." + d2Service + "", "true"); } - if(searchData.getVnfType() != null){ - searchKeyValue.put(jsonBodyData, "*"+searchData.getVnfType()+"*"); + if (searchData.getVnfType() != null) { + searchKeyValue.put(jsonBodyData, "*" + searchData.getVnfType() + "*"); } - if(searchData.getPolicyStatus() != null){ - searchKeyValue.put(jsonBodyData, "*"+searchData.getPolicyStatus()+"*"); + if (searchData.getPolicyStatus() != null) { + searchKeyValue.put(jsonBodyData, "*" + searchData.getPolicyStatus() + "*"); } - if(searchData.getVproAction() != null){ - searchKeyValue.put(jsonBodyData, "*"+searchData.getVproAction()+"*"); + if (searchData.getVproAction() != null) { + searchKeyValue.put(jsonBodyData, "*" + searchData.getVproAction() + "*"); } - if(searchData.getServiceType() != null){ + if (searchData.getServiceType() != null) { searchKeyValue.put("serviceType", searchData.getServiceType()); } - if(searchData.getBindTextSearch() != null){ + if (searchData.getBindTextSearch() != null) { searchKeyValue.put(searchData.getBindTextSearch(), searchText); searchText = null; } PolicyIndexType type = null; - if(policyType != null){ - if(action.equalsIgnoreCase(policyType)){ + if (policyType != null) { + if (action.equalsIgnoreCase(policyType)) { type = ElkConnector.PolicyIndexType.action; - }else if(decision.equalsIgnoreCase(policyType)){ + } else if (decision.equalsIgnoreCase(policyType)) { type = ElkConnector.PolicyIndexType.decision; - }else if(config.equalsIgnoreCase(policyType)){ + } else if (config.equalsIgnoreCase(policyType)) { type = ElkConnector.PolicyIndexType.config; - }else if("closedloop".equalsIgnoreCase(policyType)){ + } else if ("closedloop".equalsIgnoreCase(policyType)) { type = ElkConnector.PolicyIndexType.closedloop; - }else{ + } else { type = ElkConnector.PolicyIndexType.all; } - }else{ + } else { type = ElkConnector.PolicyIndexType.all; } - if(validationCheck){ + if (validationCheck) { JestResult policyResultList = controller.search(type, searchText, searchKeyValue); - if(policyResultList.isSucceeded()){ + if (policyResultList.isSucceeded()) { result = true; policyResult = true; - JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); - for(int i =0; i < resultObject.size(); i++){ + JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject() + .get("hits").getAsJsonArray(); + for (int i = 0; i < resultObject.size(); i++) { String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); policyList.add(policyName); } - }else{ - LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); + } else { + LOGGER.error( + "Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); } } - }catch(Exception e){ + } catch (Exception e) { LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server" + e); } } - if(validationCheck){ - if(result){ + if (validationCheck) { + if (result) { message = "Elastic Server Transaction is success"; - }else{ + } else { message = "Elastic Server Transaction is failed, please check the logs"; } } @@ -298,22 +300,25 @@ public class PolicyElasticSearchController{ JSONObject j = new JSONObject(msg); response.setStatus(HttpServletResponse.SC_OK); response.addHeader(success, success); - if(policyResult){ + if (policyResult) { JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); response.getWriter().write(k.toString()); - }else{ + } else { response.getWriter().write(j.toString()); } - }catch(Exception e){ + } catch (Exception e) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader("error", "Exception Occured While Performing Elastic Transaction"); - LOGGER.error("Exception Occured While Performing Elastic Transaction"+e.getMessage(),e); + LOGGER.error("Exception Occured While Performing Elastic Transaction" + e.getMessage(), e); } } - @RequestMapping(value={"/searchDictionary"}, method={org.springframework.web.bind.annotation.RequestMethod.POST}) - public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, IOException { - try{ + @RequestMapping( + value = {"/searchDictionary"}, + method = {org.springframework.web.bind.annotation.RequestMethod.POST}) + public ModelAndView searchDictionary(HttpServletRequest request, HttpServletResponse response) + throws UnsupportedEncodingException, IOException { + try { PolicyIndexType config = PolicyIndexType.config; PolicyIndexType closedloop = PolicyIndexType.closedloop; PolicyIndexType action = PolicyIndexType.action; @@ -327,105 +332,114 @@ public class PolicyElasticSearchController{ Mode mode = Mode.valueOf(dictionaryType); String value; List<String> policyList = new ArrayList<>(); - switch (mode){ - case attribute : - Attribute attributedata = mapper.readValue(root.get("data").toString(), Attribute.class); - value = attributedata.getXacmlId(); - policyList = searchElkDatabase(all, pholder,value); - break; - case onapName : - OnapName onapName = mapper.readValue(root.get("data").toString(), OnapName.class); - value = onapName.getOnapName(); - policyList = searchElkDatabase(all, "onapName",value); - break; - case actionPolicy : - ActionPolicyDict actionPolicyDict = mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); - value = actionPolicyDict.getAttributeName(); - policyList = searchElkDatabase(action, "actionAttributeValue",value); - break; - case brmsParam : - BRMSParamTemplate bRMSParamTemplate = mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); - value = bRMSParamTemplate.getRuleName(); - policyList = searchElkDatabase(config, "ruleName",value); - break; - case pepOptions : - PEPOptions pEPOptions = mapper.readValue(root.get("data").toString(), PEPOptions.class); - value = pEPOptions.getPepName(); - policyList = searchElkDatabase(closedloop,"jsonBodyData.pepName",value); - break; - case clSite : - ClosedLoopSite closedLoopSite = mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); - value = closedLoopSite.getSiteName(); - policyList = searchElkDatabase(closedloop,"siteNames",value); - break; - case clService : - ClosedLoopD2Services closedLoopD2Services = mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); - value = closedLoopD2Services.getServiceName(); - policyList = searchElkDatabase(closedloop, pholder,value); - break; - case clVarbind : - VarbindDictionary varbindDictionary = mapper.readValue(root.get("data").toString(), VarbindDictionary.class); - value = varbindDictionary.getVarbindName(); - policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); - break; - case clVnf : - VNFType vNFType = mapper.readValue(root.get("data").toString(), VNFType.class); - value = vNFType.getVnftype(); - policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); - break; - case clVSCL : - VSCLAction vsclAction = mapper.readValue(root.get("data").toString(), VSCLAction.class); - value = vsclAction.getVsclaction(); - policyList = searchElkDatabase(closedloop, jsonBodyData,"*"+value+"*"); - break; - case decision : - DecisionSettings decisionSettings = mapper.readValue(root.get("data").toString(), DecisionSettings.class); - value = decisionSettings.getXacmlId(); - policyList = searchElkDatabase(decision,pholder,value); - break; - case fwTerm : - TermList term = mapper.readValue(root.get("data").toString(), TermList.class); - value = term.getTermName(); - policyList = searchElkDatabase(config, pholder,value); - break; - case msDCAEUUID : - DCAEuuid dcaeUUID = mapper.readValue(root.get("data").toString(), DCAEuuid.class); - value = dcaeUUID.getName(); - policyList = searchElkDatabase(config, "uuid",value); - break; - case msLocation : - MicroServiceLocation mslocation = mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); - value = mslocation.getName(); - policyList = searchElkDatabase(config, "location",value); - break; - case msModels : - MicroServiceModels msModels = mapper.readValue(root.get("data").toString(), MicroServiceModels.class); - value = msModels.getModelName(); - policyList = searchElkDatabase(config, "serviceType",value); - break; - case psGroupPolicy : - GroupPolicyScopeList groupPoilicy = mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); - value = groupPoilicy.getGroupName(); - policyList = searchElkDatabase(config, pholder,value); - break; - case safeRisk : - RiskType riskType= mapper.readValue(root.get("data").toString(), RiskType.class); - value = riskType.getRiskName(); - policyList = searchElkDatabase(config, "riskType",value); - break; - case safePolicyWarning : - SafePolicyWarning safePolicy = mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); - value = safePolicy.getName(); - policyList = searchElkDatabase(config, pholder,value); - break; - default: + switch (mode) { + case attribute: + Attribute attributedata = mapper.readValue(root.get("data").toString(), Attribute.class); + value = attributedata.getXacmlId(); + policyList = searchElkDatabase(all, pholder, value); + break; + case onapName: + OnapName onapName = mapper.readValue(root.get("data").toString(), OnapName.class); + value = onapName.getOnapName(); + policyList = searchElkDatabase(all, "onapName", value); + break; + case actionPolicy: + ActionPolicyDict actionPolicyDict = + mapper.readValue(root.get("data").toString(), ActionPolicyDict.class); + value = actionPolicyDict.getAttributeName(); + policyList = searchElkDatabase(action, "actionAttributeValue", value); + break; + case brmsParam: + BRMSParamTemplate bRMSParamTemplate = + mapper.readValue(root.get("data").toString(), BRMSParamTemplate.class); + value = bRMSParamTemplate.getRuleName(); + policyList = searchElkDatabase(config, "ruleName", value); + break; + case pepOptions: + PEPOptions pEPOptions = mapper.readValue(root.get("data").toString(), PEPOptions.class); + value = pEPOptions.getPepName(); + policyList = searchElkDatabase(closedloop, "jsonBodyData.pepName", value); + break; + case clSite: + ClosedLoopSite closedLoopSite = mapper.readValue(root.get("data").toString(), ClosedLoopSite.class); + value = closedLoopSite.getSiteName(); + policyList = searchElkDatabase(closedloop, "siteNames", value); + break; + case clService: + ClosedLoopD2Services closedLoopD2Services = + mapper.readValue(root.get("data").toString(), ClosedLoopD2Services.class); + value = closedLoopD2Services.getServiceName(); + policyList = searchElkDatabase(closedloop, pholder, value); + break; + case clVarbind: + VarbindDictionary varbindDictionary = + mapper.readValue(root.get("data").toString(), VarbindDictionary.class); + value = varbindDictionary.getVarbindName(); + policyList = searchElkDatabase(closedloop, jsonBodyData, "*" + value + "*"); + break; + case clVnf: + VNFType vNFType = mapper.readValue(root.get("data").toString(), VNFType.class); + value = vNFType.getVnftype(); + policyList = searchElkDatabase(closedloop, jsonBodyData, "*" + value + "*"); + break; + case clVSCL: + VSCLAction vsclAction = mapper.readValue(root.get("data").toString(), VSCLAction.class); + value = vsclAction.getVsclaction(); + policyList = searchElkDatabase(closedloop, jsonBodyData, "*" + value + "*"); + break; + case decision: + DecisionSettings decisionSettings = + mapper.readValue(root.get("data").toString(), DecisionSettings.class); + value = decisionSettings.getXacmlId(); + policyList = searchElkDatabase(decision, pholder, value); + break; + case fwTerm: + TermList term = mapper.readValue(root.get("data").toString(), TermList.class); + value = term.getTermName(); + policyList = searchElkDatabase(config, pholder, value); + break; + case msDCAEUUID: + DCAEuuid dcaeUUID = mapper.readValue(root.get("data").toString(), DCAEuuid.class); + value = dcaeUUID.getName(); + policyList = searchElkDatabase(config, "uuid", value); + break; + case msLocation: + MicroServiceLocation mslocation = + mapper.readValue(root.get("data").toString(), MicroServiceLocation.class); + value = mslocation.getName(); + policyList = searchElkDatabase(config, "location", value); + break; + case msModels: + MicroServiceModels msModels = + mapper.readValue(root.get("data").toString(), MicroServiceModels.class); + value = msModels.getModelName(); + policyList = searchElkDatabase(config, "serviceType", value); + break; + case psGroupPolicy: + GroupPolicyScopeList groupPoilicy = + mapper.readValue(root.get("data").toString(), GroupPolicyScopeList.class); + value = groupPoilicy.getGroupName(); + policyList = searchElkDatabase(config, pholder, value); + break; + case safeRisk: + RiskType riskType = mapper.readValue(root.get("data").toString(), RiskType.class); + value = riskType.getRiskName(); + policyList = searchElkDatabase(config, "riskType", value); + break; + case safePolicyWarning: + SafePolicyWarning safePolicy = + mapper.readValue(root.get("data").toString(), SafePolicyWarning.class); + value = safePolicy.getName(); + policyList = searchElkDatabase(config, pholder, value); + break; + default: } response.setStatus(HttpServletResponse.SC_OK); response.addHeader(success, success); JSONObject k = new JSONObject("{policyresult: " + policyList + "}"); response.getWriter().write(k.toString()); - }catch(Exception e){ + } catch (Exception e) { response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); @@ -435,30 +449,31 @@ public class PolicyElasticSearchController{ return null; } - //Search the Elk database - public List<String> searchElkDatabase(PolicyIndexType type, String key, String value){ + // Search the Elk database + public List<String> searchElkDatabase(PolicyIndexType type, String key, String value) { PolicyElasticSearchController controller = new PolicyElasticSearchController(); Map<String, String> searchKeyValue = new HashMap<>(); - if(!pholder.equals(key)){ + if (!pholder.equals(key)) { searchKeyValue.put(key, value); } List<String> policyList = new ArrayList<>(); JestResult policyResultList = controller.search(type, value, searchKeyValue); - if(policyResultList.isSucceeded()){ - JsonArray resultObject = policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); - for(int i =0; i < resultObject.size(); i++){ + if (policyResultList.isSucceeded()) { + JsonArray resultObject = + policyResultList.getJsonObject().get("hits").getAsJsonObject().get("hits").getAsJsonArray(); + for (int i = 0; i < resultObject.size(); i++) { String policyName = resultObject.get(i).getAsJsonObject().get("_id").toString(); policyList.add(policyName); } - }else{ + } else { LOGGER.error("Exception Occured While Searching for Data in Elastic Search Server, Check the Logs"); } return policyList; } public JestResult search(PolicyIndexType type, String text, Map<String, String> searchKeyValue) { - return ElkConnector.singleton.search(type, text, searchKeyValue); + return ElkConnector.singleton.search(type, text, searchKeyValue); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java index 9338cdbbd..95930ede8 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/elk/client/PolicyLocator.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk.client; public class PolicyLocator { @@ -27,11 +28,10 @@ public class PolicyLocator { public final String policyId; public final String version; - public PolicyLocator(String policyType, String policyName, - String owner, String scope, String policyId, - String version) { + public PolicyLocator(String policyType, String policyName, String owner, String scope, String policyId, + String version) { this.policyType = policyType; - this.policyName= policyName; + this.policyName = policyName; this.owner = owner; this.scope = scope; this.policyId = policyId; @@ -39,13 +39,8 @@ public class PolicyLocator { } public String toString() { - return "[" + - this.owner + "|" + - this.scope + "|" + - this.policyType + "|" + - this.policyName + "|" + - this.policyId + "|" + - "v" + this.version + "|" + "]"; + return "[" + this.owner + "|" + this.scope + "|" + this.policyType + "|" + this.policyName + "|" + this.policyId + + "|" + "v" + this.version + "|" + "]"; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java index 46c2b1160..4baa13fda 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/APIRequestHandler.java @@ -21,8 +21,10 @@ package org.onap.policy.pap.xacml.rest.handler; import java.io.IOException; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.OnapLoggingContext; import org.onap.policy.pap.xacml.rest.service.ImportService; import org.onap.policy.pap.xacml.rest.service.MetricService; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java index fd98279e9..a5e61b9a0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandler.java @@ -23,13 +23,16 @@ package org.onap.policy.pap.xacml.rest.handler; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.api.pap.PDPPolicy; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.List; + import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.lang3.StringUtils; import org.onap.policy.common.logging.OnapLoggingContext; import org.onap.policy.common.logging.eelf.MessageCodes; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java index 89ce18835..e9edde66c 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandler.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,16 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.handler; +import com.att.research.xacml.util.XACMLProperties; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; -import com.att.research.xacml.util.XACMLProperties; - public interface DictionaryHandler { public static final Logger logger = FlexLogger.getLogger(DictionaryHandler.class); String DICTIONARY_DEFAULT_CLASS = DictionaryHandlerImpl.class.getName(); @@ -34,13 +35,14 @@ public interface DictionaryHandler { /* * Get Instance */ - public static DictionaryHandler getInstance(){ + public static DictionaryHandler getInstance() { try { - Class<?> dictionaryHandler = Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS)); + Class<?> dictionaryHandler = + Class.forName(XACMLProperties.getProperty("dictionary.impl.className", DICTIONARY_DEFAULT_CLASS)); DictionaryHandler instance = (DictionaryHandler) dictionaryHandler.newInstance(); return instance; } catch (Exception e) { - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } return null; } @@ -49,6 +51,7 @@ public interface DictionaryHandler { * Get Equivalent for Dictionary Services. */ public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response); + /* * Put Equivalent for Dictionary Services. */ @@ -59,7 +62,9 @@ public interface DictionaryHandler { * * getflag=true indicates Get Request. * getflag=false indicates Put Request. + * * @return */ - public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, boolean getflag); + public String extendedOptions(String dictionaryType, HttpServletRequest request, HttpServletResponse response, + boolean getflag); } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java index 5fc737887..65c50b1c0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerImpl.java @@ -22,6 +22,7 @@ package org.onap.policy.pap.xacml.rest.handler; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.pap.xacml.rest.service.DictionaryService; @@ -313,7 +314,7 @@ public class DictionaryHandlerImpl implements DictionaryHandler { response.addHeader("error", message); return; } - if(("Success").equalsIgnoreCase(result)) { + if (("Success").equalsIgnoreCase(result)) { response.setStatus(HttpServletResponse.SC_OK); response.addHeader("successMapKey", "success"); if (operation.equalsIgnoreCase("update")) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java index ed1c57369..81da91107 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandler.java @@ -21,12 +21,15 @@ package org.onap.policy.pap.xacml.rest.handler; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.net.URI; import java.util.List; + import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -104,21 +107,22 @@ public class PushPolicyHandler { } } - public boolean preSafetyCheck(StdPDPPolicy policy, String configHome){ + public boolean preSafetyCheck(StdPDPPolicy policy, String configHome) { return true; } - public boolean preSafetyCheck(OnapPDPGroup policy, String configHome){ + public boolean preSafetyCheck(OnapPDPGroup policy, String configHome) { return true; } public static PushPolicyHandler getInstance() { try { - Class<?> pushPolicyHandler = Class.forName(XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName())); + Class<?> pushPolicyHandler = Class.forName( + XACMLProperties.getProperty("pushPolicy.impl.className", PushPolicyHandler.class.getName())); PushPolicyHandler instance = (PushPolicyHandler) pushPolicyHandler.newInstance(); return instance; } catch (Exception e) { - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } return null; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java index 90f8b5a70..8a7c60490 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/handler/SavePolicyHandler.java @@ -21,12 +21,15 @@ package org.onap.policy.pap.xacml.rest.handler; import com.att.research.xacml.util.XACMLProperties; + import java.io.IOException; import java.util.HashMap; + import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.ParserConfigurationException; + import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -45,11 +48,11 @@ public class SavePolicyHandler { String policyType = request.getParameter("policyType"); String apiflag = request.getParameter("apiflag"); PolicyCreation creation = new PolicyCreation(); - if ( policyType != null ) { + if (policyType != null) { PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); - if("update".equalsIgnoreCase(operation)){ + if ("update".equalsIgnoreCase(operation)) { policyAdapter.setEditPolicy(true); - }else{ + } else { policyAdapter.setEditPolicy(false); } @@ -58,10 +61,10 @@ public class SavePolicyHandler { // 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(request.getInputStream()); scanner.useDelimiter("\\A"); - json = scanner.hasNext() ? scanner.next() : ""; + json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); - if(policyAdapter.isEditPolicy()){ + if (policyAdapter.isEditPolicy()) { PolicyLogger.info("SavePolicyHandler: JSON request from API to update a policy: " + json); } else { PolicyLogger.info("SavePolicyHandler: JSON request from API to create a policy: " + json); @@ -69,67 +72,68 @@ public class SavePolicyHandler { // convert Object sent as JSON into local object StdPAPPolicy policy = PolicyUtils.jsonStringToObject(json, StdPAPPolicy.class); - //Set policyAdapter values including parentPath (Common to all policy types) + // Set policyAdapter values including parentPath (Common to all policy types) try { PolicyLogger.info("SavePolicyHandler: Setting parameter values to PolicyAdapter"); policyAdapter = setDataToPolicyAdapter(policy, policyType, apiflag); - if(!extendedPolicyOptions(policyAdapter, response)){ + if (!extendedPolicyOptions(policyAdapter, response)) { creation.savePolicy(policyAdapter, response); } if ("update".equalsIgnoreCase(operation)) { - response.addHeader("operation", "update"); + response.addHeader("operation", "update"); } else { response.addHeader("operation", "create"); } } catch (Exception e1) { - logger.error("Could not set data to policy adapter "+e1.getMessage(),e1); + logger.error("Could not set data to policy adapter " + e1.getMessage(), e1); } } } - private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) throws ParserConfigurationException, ServletException, SAXException, IOException{ + private PolicyRestAdapter setDataToPolicyAdapter(StdPAPPolicy policy, String policyType, String apiflag) + throws ParserConfigurationException, ServletException, SAXException, IOException { PolicyRestAdapter policyAdapter = new PolicyRestAdapter(); policyAdapter.setApiflag(apiflag); /* * set policy adapter values for Building JSON object containing policy data */ - //Common among policy types + // Common among policy types policyAdapter.setPolicyName(policy.getPolicyName()); policyAdapter.setPolicyDescription(policy.getPolicyDescription()); - policyAdapter.setOnapName(policy.getOnapName()); //Config Base and Decision Policies + policyAdapter.setOnapName(policy.getOnapName()); // Config Base and Decision Policies policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); policyAdapter.setPolicyType(policyType); policyAdapter.setDynamicFieldConfigAttributes(policy.getDynamicFieldConfigAttributes()); policyAdapter.setEditPolicy(policy.isEditPolicy()); - //Config Specific - policyAdapter.setConfigName(policy.getConfigName()); //Base and Firewall - policyAdapter.setConfigBodyData(policy.getConfigBodyData()); //Base - policyAdapter.setConfigType((policy.getConfigType()!=null) ? policy.getConfigType().toUpperCase(): null); //Base - policyAdapter.setJsonBody(policy.getJsonBody()); //Firewall, ClosedLoop + // Config Specific + policyAdapter.setConfigName(policy.getConfigName()); // Base and Firewall + policyAdapter.setConfigBodyData(policy.getConfigBodyData()); // Base + policyAdapter.setConfigType((policy.getConfigType() != null) ? policy.getConfigType().toUpperCase() : null); // Base + policyAdapter.setJsonBody(policy.getJsonBody()); // Firewall, ClosedLoop policyAdapter.setConfigPolicyType(policy.getConfigPolicyType()); - policyAdapter.setDraft(policy.isDraft()); //ClosedLoop_Fault - policyAdapter.setServiceType(policy.getServiceType()); //ClosedLoop_PM - policyAdapter.setUuid(policy.getUuid()); //Micro Service - policyAdapter.setLocation(policy.getMsLocation()); //Micro Service - policyAdapter.setPriority(policy.getPriority()); //Micro Service + policyAdapter.setDraft(policy.isDraft()); // ClosedLoop_Fault + policyAdapter.setServiceType(policy.getServiceType()); // ClosedLoop_PM + policyAdapter.setUuid(policy.getUuid()); // Micro Service + policyAdapter.setLocation(policy.getMsLocation()); // Micro Service + policyAdapter.setPriority(policy.getPriority()); // Micro Service policyAdapter.setPolicyScope(policy.getDomainDir()); - policyAdapter.setRiskType(policy.getRiskType()); //Safe Policy Attributes - policyAdapter.setRiskLevel(policy.getRiskLevel());//Safe Policy Attributes - policyAdapter.setGuard(policy.getGuard());//Safe Policy Attributes - policyAdapter.setTtlDate(policy.getTTLDate());//Safe Policy Attributes + policyAdapter.setRiskType(policy.getRiskType()); // Safe Policy Attributes + policyAdapter.setRiskLevel(policy.getRiskLevel());// Safe Policy Attributes + policyAdapter.setGuard(policy.getGuard());// Safe Policy Attributes + policyAdapter.setTtlDate(policy.getTTLDate());// Safe Policy Attributes policyAdapter.setBrmsParamBody(policy.getDrlRuleAndUIParams()); policyAdapter.setBrmsDependency(policy.getBrmsDependency()); // BRMS Policies. policyAdapter.setBrmsController(policy.getBrmsController()); // BRMS Policies. - //Action Policy Specific - policyAdapter.setActionAttribute(policy.getActionAttribute()); //comboDictValue + // Action Policy Specific + policyAdapter.setActionAttribute(policy.getActionAttribute()); // comboDictValue policyAdapter.setActionPerformer(policy.getActionPerformer()); policyAdapter.setDynamicRuleAlgorithmLabels(policy.getDynamicRuleAlgorithmLabels()); policyAdapter.setDynamicRuleAlgorithmCombo(policy.getDynamicRuleAlgorithmCombo()); policyAdapter.setDynamicRuleAlgorithmField1(policy.getDynamicRuleAlgorithmField1()); policyAdapter.setDynamicRuleAlgorithmField2(policy.getDynamicRuleAlgorithmField2()); - //Decision Policy Specific + // Decision Policy Specific policyAdapter.setDynamicSettingsMap(policy.getDynamicSettingsMap()); policyAdapter.setRuleProvider(policy.getProviderComboBox()); policyAdapter.setDomainDir(policyAdapter.getPolicyScope()); @@ -139,24 +143,25 @@ public class SavePolicyHandler { return policyAdapter; } - public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response){ + public boolean extendedPolicyOptions(PolicyRestAdapter policyAdapter, HttpServletResponse response) { return false; } - public void addErrorHeader(String key, String value){ - if(ErrorHeaders==null){ - ErrorHeaders= new HashMap<>(); + public void addErrorHeader(String key, String value) { + if (ErrorHeaders == null) { + ErrorHeaders = new HashMap<>(); } ErrorHeaders.put(key, value); } public static SavePolicyHandler getInstance() { try { - Class<?> savePolicyHandler = Class.forName(XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName())); + Class<?> savePolicyHandler = Class.forName( + XACMLProperties.getProperty("savePolicy.impl.className", SavePolicyHandler.class.getName())); SavePolicyHandler instance = (SavePolicyHandler) savePolicyHandler.newInstance(); return instance; } catch (Exception e) { - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } return null; } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java index 42c815aa8..b83db1f07 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicy.java @@ -21,9 +21,11 @@ package org.onap.policy.pap.xacml.rest.model; import com.att.research.xacml.api.pap.PDPPolicy; + import java.util.Collection; import java.util.HashSet; import java.util.Set; + import org.onap.policy.rest.util.PDPPolicyContainer; import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPGroup; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java index 51d988887..f5ade96ac 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/model/package-info.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,4 +17,5 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.model; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java index d8a77269c..fd1764e69 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/PolicyCreation.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.policycontroller; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.File; import java.util.Date; import java.util.HashMap; @@ -28,8 +29,10 @@ import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.lang.StringUtils; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -68,12 +71,11 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; - @RestController @RequestMapping("/") -public class PolicyCreation extends AbstractPolicyCreation{ +public class PolicyCreation extends AbstractPolicyCreation { - private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class); + private static final Logger LOGGER = FlexLogger.getLogger(PolicyCreation.class); private String ruleID = ""; private PolicyDBDao policyDBDao; @@ -90,15 +92,16 @@ public class PolicyCreation extends AbstractPolicyCreation{ } @Autowired - public PolicyCreation(CommonClassDao commonClassDao){ + public PolicyCreation(CommonClassDao commonClassDao) { PolicyCreation.commonClassDao = commonClassDao; } - public PolicyCreation(){} + public PolicyCreation() { + } - @RequestMapping(value="/policycreation/save_policy", method = RequestMethod.POST) + @RequestMapping(value = "/policycreation/save_policy", method = RequestMethod.POST) @ResponseBody - public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response){ + public ResponseEntity<String> savePolicy(@RequestBody PolicyRestAdapter policyData, HttpServletResponse response) { String body = null; HttpStatus status = HttpStatus.BAD_REQUEST; Map<String, String> successMap = new HashMap<>(); @@ -110,9 +113,9 @@ public class PolicyCreation extends AbstractPolicyCreation{ String policyConfigType = null; String userId = policyData.getUserId(); - if (policyData.getTtlDate()==null){ + if (policyData.getTtlDate() == null) { policyData.setTtlDate("NA"); - }else{ + } else { String dateTTL = policyData.getTtlDate(); String newDate = convertDate(dateTTL); policyData.setTtlDate(newDate); @@ -125,19 +128,19 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyConfigType = policyData.getConfigPolicyType(); if ("Firewall Config".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_FW_"; - }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_Fault_"; - }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_PM_"; - }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { + } else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_MS_"; - }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { + } else if ("Optimization".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_OOF_"; - }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { + } else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_BRMS_Raw_"; - }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { + } else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { filePrefix = "Config_BRMS_Param_"; - }else { + } else { filePrefix = "Config_"; } } else if ("Action".equalsIgnoreCase(policyType)) { @@ -151,8 +154,9 @@ public class PolicyCreation extends AbstractPolicyCreation{ String createdBy; String modifiedBy; String scopeCheck = policyData.getDomainDir().replace(".", File.separator); - PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao.getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck); - if(policyEditorScope == null){ + PolicyEditorScopes policyEditorScope = (PolicyEditorScopes) commonClassDao + .getEntityItem(PolicyEditorScopes.class, "scopeName", scopeCheck); + if (policyEditorScope == null) { UserInfo userInfo = new UserInfo(); userInfo.setUserName("API"); userInfo.setUserLoginId("API"); @@ -162,21 +166,22 @@ public class PolicyCreation extends AbstractPolicyCreation{ editorScope.setUserModifiedBy(userInfo); commonClassDao.save(editorScope); } - //get the highest version of policy from policy version table. - String dbCheckPolicyName = policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName(); + // get the highest version of policy from policy version table. + String dbCheckPolicyName = + policyData.getDomainDir() + File.separator + filePrefix + policyData.getPolicyName(); PolicyVersion policyVersion = getPolicyVersionData(dbCheckPolicyName); - if(policyVersion == null){ + if (policyVersion == null) { highestVersion = 0; - }else{ + } else { highestVersion = policyVersion.getHigherVersion(); } - if(highestVersion != 0 && policyVersion != null){ - if(policyData.isEditPolicy()){ - version = highestVersion +1; - if(userId ==null){ + if (highestVersion != 0 && policyVersion != null) { + if (policyData.isEditPolicy()) { + version = highestVersion + 1; + if (userId == null) { modifiedBy = "API"; - }else{ + } else { modifiedBy = userId; } policyData.setUserId("API"); @@ -186,7 +191,7 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyVersionDao.setHigherVersion(version); policyVersionDao.setModifiedBy(modifiedBy); policyVersionDao.setModifiedDate(new Date()); - }else{ + } else { body = "policyExists"; status = HttpStatus.CONFLICT; response.setStatus(HttpServletResponse.SC_CONFLICT); @@ -194,22 +199,23 @@ public class PolicyCreation extends AbstractPolicyCreation{ response.addHeader("policyName", policyData.getPolicyName()); return new ResponseEntity<>(body, status); } - }else{ + } else { // if policy does not exist and the request is updatePolicy return error - if(policyData.isEditPolicy()){ + if (policyData.isEditPolicy()) { body = "policyNotAvailableForEdit"; status = HttpStatus.NOT_FOUND; response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.addHeader("error", body); - response.addHeader("message", policyData.getPolicyName() + " does not exist on the PAP and cannot be updated."); + response.addHeader("message", + policyData.getPolicyName() + " does not exist on the PAP and cannot be updated."); return new ResponseEntity<>(body, status); } version = 1; - if(userId == null){ + if (userId == null) { createdBy = "API"; modifiedBy = "API"; policyData.setUserId("API"); - }else{ + } else { createdBy = userId; modifiedBy = userId; policyData.setUserId("API"); @@ -225,15 +231,16 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyData.setPolicyID(newPolicyID()); policyData.setRuleID(ruleID); - String policyFileName = dbCheckPolicyName.replace(File.separator, ".")+ "." + version + ".xml"; + String policyFileName = dbCheckPolicyName.replace(File.separator, ".") + "." + version + ".xml"; policyData.setNewFileName(policyFileName); - policyData.setPolicyDescription(policyData.getPolicyDescription()+ "@CreatedBy:" +createdBy + "@CreatedBy:" + "@ModifiedBy:" +modifiedBy + "@ModifiedBy:"); + policyData.setPolicyDescription(policyData.getPolicyDescription() + "@CreatedBy:" + createdBy + + "@CreatedBy:" + "@ModifiedBy:" + modifiedBy + "@ModifiedBy:"); policyData.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); - if(policyData.getApiflag() == null){ - //set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON - if(policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()){ - for(Object attribute : policyData.getAttributes()){ - if(attribute instanceof LinkedHashMap<?, ?>){ + if (policyData.getApiflag() == null) { + // set the Rule Combining Algorithm Id to be sent to PAP-REST via JSON + if (policyData.getAttributes() != null && !policyData.getAttributes().isEmpty()) { + for (Object attribute : policyData.getAttributes()) { + if (attribute instanceof LinkedHashMap<?, ?>) { String key = ((LinkedHashMap<?, ?>) attribute).get("key").toString(); String value = ((LinkedHashMap<?, ?>) attribute).get("value").toString(); attributeMap.put(key, value); @@ -250,34 +257,37 @@ public class PolicyCreation extends AbstractPolicyCreation{ if ("Config".equalsIgnoreCase(policyType)) { if ("Firewall Config".equalsIgnoreCase(policyConfigType)) { newPolicy = new FirewallConfigPolicy(policyData); - }else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { + } else if ("BRMS_Raw".equalsIgnoreCase(policyConfigType)) { policyData.setOnapName("DROOLS"); policyData.setConfigName("BRMS_RAW_RULE"); newPolicy = new CreateBrmsRawPolicy(policyData); - }else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { + } else if ("BRMS_Param".equalsIgnoreCase(policyConfigType)) { policyData.setOnapName("DROOLS"); policyData.setConfigName("BRMS_PARAM_RULE"); Map<String, String> drlRuleAndUIParams = new HashMap<>(); - if(policyData.getApiflag() == null){ + if (policyData.getApiflag() == null) { // If there is any dynamic field create the matches here - String key="templateName"; - String value= policyData.getRuleName(); + String key = "templateName"; + String value = policyData.getRuleName(); drlRuleAndUIParams.put(key, value); - if(policyData.getRuleData().size() > 0){ - for(Object keyValue: policyData.getRuleData().keySet()){ - drlRuleAndUIParams.put(keyValue.toString(), policyData.getRuleData().get(keyValue).toString()); + if (policyData.getRuleData().size() > 0) { + for (Object keyValue : policyData.getRuleData().keySet()) { + drlRuleAndUIParams.put(keyValue.toString(), + policyData.getRuleData().get(keyValue).toString()); } } policyData.setBrmsParamBody(drlRuleAndUIParams); - }else{ - drlRuleAndUIParams=policyData.getBrmsParamBody(); - String modelName= drlRuleAndUIParams.get("templateName"); - PolicyLogger.info("Template name from API is: "+modelName); - - BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao.getEntityItem(BRMSParamTemplate.class, "ruleName", modelName); - if(template == null){ - String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " - + modelName + " was not found in the dictionary."; + } else { + drlRuleAndUIParams = policyData.getBrmsParamBody(); + String modelName = drlRuleAndUIParams.get("templateName"); + PolicyLogger.info("Template name from API is: " + modelName); + + BRMSParamTemplate template = (BRMSParamTemplate) commonClassDao + .getEntityItem(BRMSParamTemplate.class, "ruleName", modelName); + if (template == null) { + String message = + XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Template. The template name, " + + modelName + " was not found in the dictionary."; body = message; status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); @@ -287,40 +297,44 @@ public class PolicyCreation extends AbstractPolicyCreation{ } } newPolicy = new CreateBrmsParamPolicy(policyData); - }else if ("Base".equalsIgnoreCase(policyConfigType)) { - newPolicy = new ConfigPolicy(policyData); - }else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { + } else if ("Base".equalsIgnoreCase(policyConfigType)) { + newPolicy = new ConfigPolicy(policyData); + } else if ("ClosedLoop_Fault".equalsIgnoreCase(policyConfigType)) { newPolicy = new ClosedLoopPolicy(policyData); - }else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { - if(policyData.getApiflag() == null){ - policyData.setServiceType(policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); + } else if ("ClosedLoop_PM".equalsIgnoreCase(policyConfigType)) { + if (policyData.getApiflag() == null) { + policyData.setServiceType( + policyData.getServiceTypePolicyName().get("serviceTypePolicyName").toString()); ObjectMapper jsonMapper = new ObjectMapper(); String jsonBody = jsonMapper.writeValueAsString(policyData.getJsonBodyData()); - jsonBody = jsonBody.replaceFirst("\\{", "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); + jsonBody = jsonBody.replaceFirst("\\{", + "\\{\"serviceTypePolicyName\": \"serviceTypeFieldValue\","); jsonBody = jsonBody.replace("serviceTypeFieldValue", policyData.getServiceType()); policyData.setJsonBody(jsonBody); } newPolicy = new CreateClosedLoopPerformanceMetrics(policyData); - }else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { + } else if ("Micro Service".equalsIgnoreCase(policyConfigType)) { newPolicy = new MicroServiceConfigPolicy(policyData); - }else if ("Optimization".equalsIgnoreCase(policyConfigType)) { + } else if ("Optimization".equalsIgnoreCase(policyConfigType)) { newPolicy = new OptimizationConfigPolicy(policyData); } - }else if("Action".equalsIgnoreCase(policyType)) { - if(policyData.getApiflag() == null){ + } else if ("Action".equalsIgnoreCase(policyType)) { + if (policyData.getApiflag() == null) { List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); List<String> dynamicRuleAlgorithmCombo = new LinkedList<>(); List<String> dynamicRuleAlgorithmField1 = new LinkedList<>(); List<String> dynamicRuleAlgorithmField2 = new LinkedList<>(); - - if(!policyData.getRuleAlgorithmschoices().isEmpty()){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap<?, ?>){ + if (!policyData.getRuleAlgorithmschoices().isEmpty()) { + for (Object attribute : policyData.getRuleAlgorithmschoices()) { + if (attribute instanceof LinkedHashMap<?, ?>) { String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); - String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); - String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); + String key = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); dynamicRuleAlgorithmLabels.add(label); dynamicRuleAlgorithmField1.add(key); dynamicRuleAlgorithmCombo.add(rule); @@ -330,8 +344,9 @@ public class PolicyCreation extends AbstractPolicyCreation{ } String actionDictValue = policyData.getActionAttributeValue(); - ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", actionDictValue)); - if(jsonData!=null){ + ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, + "attributeName", actionDictValue)); + if (jsonData != null) { String actionBodyString = jsonData.getBody(); String actionDictHeader = jsonData.getHeader(); String actionDictType = jsonData.getType(); @@ -350,11 +365,12 @@ public class PolicyCreation extends AbstractPolicyCreation{ policyData.setDynamicRuleAlgorithmCombo(dynamicRuleAlgorithmCombo); policyData.setDynamicRuleAlgorithmField1(dynamicRuleAlgorithmField1); policyData.setDynamicRuleAlgorithmField2(dynamicRuleAlgorithmField2); - }else{ + } else { // API request. String comboDictValue = policyData.getActionAttribute(); - ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, "attributeName", comboDictValue)); - if(jsonData!=null){ + ActionPolicyDict jsonData = ((ActionPolicyDict) commonClassDao.getEntityItem(ActionPolicyDict.class, + "attributeName", comboDictValue)); + if (jsonData != null) { policyData.setActionBody(jsonData.getBody()); policyData.setActionDictHeader(jsonData.getHeader()); policyData.setActionDictType(jsonData.getType()); @@ -364,7 +380,7 @@ public class PolicyCreation extends AbstractPolicyCreation{ } newPolicy = new ActionPolicy(policyData, commonClassDao); } else if ("Decision".equalsIgnoreCase(policyType)) { - if(policyData.getApiflag() == null){ + if (policyData.getApiflag() == null) { Map<String, String> settingsMap = new HashMap<>(); Map<String, String> treatmentMap = new HashMap<>(); List<String> dynamicRuleAlgorithmLabels = new LinkedList<>(); @@ -376,22 +392,26 @@ public class PolicyCreation extends AbstractPolicyCreation{ List<String> errorCodeList = new LinkedList<>(); List<String> treatmentList = new LinkedList<>(); - if(!policyData.getSettings().isEmpty()){ - for(Object settingsData : policyData.getSettings()){ - if(settingsData instanceof LinkedHashMap<?, ?>){ + if (!policyData.getSettings().isEmpty()) { + for (Object settingsData : policyData.getSettings()) { + if (settingsData instanceof LinkedHashMap<?, ?>) { String key = ((LinkedHashMap<?, ?>) settingsData).get("key").toString(); String value = ((LinkedHashMap<?, ?>) settingsData).get("value").toString(); settingsMap.put(key, value); } } } - if(policyData.getRuleAlgorithmschoices()!=null && policyData.getRuleAlgorithmschoices().size() > 0){ - for(Object attribute : policyData.getRuleAlgorithmschoices()){ - if(attribute instanceof LinkedHashMap<?, ?>){ + if (policyData.getRuleAlgorithmschoices() != null + && policyData.getRuleAlgorithmschoices().size() > 0) { + for (Object attribute : policyData.getRuleAlgorithmschoices()) { + if (attribute instanceof LinkedHashMap<?, ?>) { String label = ((LinkedHashMap<?, ?>) attribute).get("id").toString(); - String key = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); - String rule = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); - String value = ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); + String key = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField1").toString(); + String rule = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmCombo").toString(); + String value = + ((LinkedHashMap<?, ?>) attribute).get("dynamicRuleAlgorithmField2").toString(); dynamicRuleAlgorithmLabels.add(label); dynamicRuleAlgorithmField1.add(key); dynamicRuleAlgorithmCombo.add(rule); @@ -470,9 +490,9 @@ public class PolicyCreation extends AbstractPolicyCreation{ newPolicy = new DecisionPolicy(policyData); } - if(newPolicy != null){ + if (newPolicy != null) { newPolicy.prepareToSave(); - }else{ + } else { body = "error"; status = HttpStatus.INTERNAL_SERVER_ERROR; response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); @@ -481,23 +501,23 @@ public class PolicyCreation extends AbstractPolicyCreation{ } PolicyDBDaoTransaction policyDBDaoTransaction = null; - try{ + try { policyDBDao = PolicyDBDao.getPolicyDBDaoInstance(); policyDBDaoTransaction = policyDBDao.getNewTransaction(); policyDBDaoTransaction.createPolicy(newPolicy, policyData.getUserId()); successMap = newPolicy.savePolicies(); - if(successMap.containsKey("success")){ + if (successMap.containsKey("success")) { policyDBDaoTransaction.commitTransaction(); - if(policyData.isEditPolicy()){ + if (policyData.isEditPolicy()) { commonClassDao.update(policyVersionDao); - }else{ + } else { commonClassDao.save(policyVersionDao); } - try{ - PolicyElasticSearchController search= new PolicyElasticSearchController(); + try { + PolicyElasticSearchController search = new PolicyElasticSearchController(); search.updateElk(policyData); - }catch(Exception e){ - LOGGER.error("Error Occured while saving policy to Elastic Database"+e); + } catch (Exception e) { + LOGGER.error("Error Occured while saving policy to Elastic Database" + e); } body = "success"; status = HttpStatus.OK; @@ -505,12 +525,12 @@ public class PolicyCreation extends AbstractPolicyCreation{ response.addHeader("successMapKey", "success"); response.addHeader("policyName", policyData.getNewFileName()); - //get message from the SafetyCheckerResults if present + // get message from the SafetyCheckerResults if present String safetyCheckerResponse = policyData.getClWarning(); String existingCLName = policyData.getExistingCLName(); - //if safetyCheckerResponse is not null add a header to send back with response - if(safetyCheckerResponse!=null) { + // if safetyCheckerResponse is not null add a header to send back with response + if (safetyCheckerResponse != null) { PolicyLogger.info("SafetyCheckerResponse message: " + safetyCheckerResponse); response.addHeader("safetyChecker", safetyCheckerResponse); response.addHeader("newCLName", CLName); @@ -519,16 +539,17 @@ public class PolicyCreation extends AbstractPolicyCreation{ PolicyLogger.info("SafetyCheckerResponse was empty or null."); } - }else if (successMap.containsKey("invalidAttribute")) { + } else if (successMap.containsKey("invalidAttribute")) { String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Invalid Action Attribute"; - LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + policyData.getActionAttribute() + " in the ActionPolicyDict table."); + LOGGER.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Could not fine " + + policyData.getActionAttribute() + " in the ActionPolicyDict table."); body = "invalidAttribute"; status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader("invalidAttribute", policyData.getActionAttribute()); response.addHeader("error", message); response.addHeader("policyName", policyData.getPolicyName()); - }else if (successMap.containsKey("fwdberror")) { + } else if (successMap.containsKey("fwdberror")) { policyDBDaoTransaction.rollbackTransaction(); body = "fwdberror"; status = HttpStatus.BAD_REQUEST; @@ -540,30 +561,28 @@ public class PolicyCreation extends AbstractPolicyCreation{ response.addHeader("policyName", policyData.getPolicyName()); } else if (successMap.get("error").equals("Validation Failed")) { policyDBDaoTransaction.rollbackTransaction(); - String message = XACMLErrorConstants.ERROR_DATA_ISSUE - + "Error Validating the Policy on the PAP."; + String message = XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Validating the Policy on the PAP."; PolicyLogger.error(message); body = "Validation"; status = HttpStatus.BAD_REQUEST; response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.addHeader("error", message); response.addHeader("policyName", policyData.getPolicyName()); - }else { + } else { policyDBDaoTransaction.rollbackTransaction(); body = "error"; status = HttpStatus.INTERNAL_SERVER_ERROR; response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); response.addHeader("error", "error"); } - }catch(Exception e){ - LOGGER.error("Exception Occured : ",e); - if(policyDBDaoTransaction != null){ + } catch (Exception e) { + LOGGER.error("Exception Occured : ", e); + if (policyDBDaoTransaction != null) { policyDBDaoTransaction.rollbackTransaction(); } } - } - catch (Exception e){ - LOGGER.error("Exception Occured : "+e.getMessage(),e); + } catch (Exception e) { + LOGGER.error("Exception Occured : " + e.getMessage(), e); body = "error"; response.addHeader("error", e.getMessage()); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); @@ -571,22 +590,23 @@ public class PolicyCreation extends AbstractPolicyCreation{ return new ResponseEntity<>(body, status); } - @ExceptionHandler({ HttpMessageNotReadableException.class }) - public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, HttpMessageNotReadableException exception) { + @ExceptionHandler({HttpMessageNotReadableException.class}) + public ResponseEntity<String> messageNotReadableExceptionHandler(HttpServletRequest req, + HttpMessageNotReadableException exception) { LOGGER.error("Request not readable: {}", exception); StringBuilder message = new StringBuilder(); message.append(exception.getMessage()); if (exception.getCause() != null) { - message.append(" Reason Caused: " - + exception.getCause().getMessage()); + message.append(" Reason Caused: " + exception.getCause().getMessage()); } return new ResponseEntity<>(message.toString(), HttpStatus.BAD_REQUEST); } - public PolicyVersion getPolicyVersionData(String dbCheckPolicyName){ - PolicyVersion entityItem = (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName); + public PolicyVersion getPolicyVersionData(String dbCheckPolicyName) { + PolicyVersion entityItem = + (PolicyVersion) commonClassDao.getEntityItem(PolicyVersion.class, "policyName", dbCheckPolicyName); if (entityItem != null) { - if(entityItem.getPolicyName().equals(dbCheckPolicyName)){ + if (entityItem.getPolicyName().equals(dbCheckPolicyName)) { return entityItem; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java index bb5307573..6c0891513 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/policycontroller/package-info.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,4 +17,5 @@ * limitations under the License. * ============LICENSE_END========================================================= */ -package org.onap.policy.pap.xacml.rest.policycontroller;
\ No newline at end of file + +package org.onap.policy.pap.xacml.rest.policycontroller; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java index 2dea96517..45e82cc54 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/DictionaryService.java @@ -21,8 +21,10 @@ package org.onap.policy.pap.xacml.rest.service; import java.io.IOException; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.pap.xacml.rest.controller.ActionPolicyDictionaryController; import org.onap.policy.pap.xacml.rest.controller.BRMSDictionaryController; import org.onap.policy.pap.xacml.rest.controller.ClosedLoopDictionaryController; @@ -37,7 +39,6 @@ import org.onap.policy.pap.xacml.rest.controller.SafePolicyController; import org.springframework.stereotype.Service; import org.springframework.web.servlet.ModelAndView; - // TODO: Auto-generated Javadoc /** * The Class DictionaryService. @@ -387,8 +388,6 @@ public class DictionaryService { return result.getViewName(); } - - /** * Save micro service location dictionary. * @@ -608,7 +607,6 @@ public class DictionaryService { return result.getViewName(); } - /** * Gets the onap dictionary. * @@ -854,7 +852,6 @@ public class DictionaryService { dictionary.getTermListDictionaryEntityData(response); } - /** * Gets the micro service location dictionary. * diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java index 01fbff7ce..d4801dfcf 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/ImportService.java @@ -30,8 +30,10 @@ import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.UUID; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; @@ -84,8 +86,7 @@ public class ImportService { response.addHeader(service, serviceName); } CreateBRMSRuleTemplate brmsRuleTemplate = new CreateBRMSRuleTemplate(); - successMap = - brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); + successMap = brmsRuleTemplate.addRule(builder.toString(), serviceName, description, "API"); } else if (("MICROSERVICE").equals(importServiceCreation)) { CreateNewMicroServiceModel newMS = null; String randomID = UUID.randomUUID().toString(); @@ -114,8 +115,7 @@ public class ImportService { } PolicyLogger.info("Request from API to import new Service"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID + type), - "utf-8"))) { + new FileOutputStream(extractDir + File.separator + randomID + type), "utf-8"))) { writer.write(xmi); } catch (IOException e) { logger.error(e); @@ -141,14 +141,12 @@ public class ImportService { inputStream.close(); } } catch (IOException e) { - PolicyLogger.error( - "Exception Occured while closing the input/output stream" + e); + PolicyLogger.error("Exception Occured while closing the input/output stream" + e); } } } - newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, - randomID); + newMS = new CreateNewMicroServiceModel(fileName, serviceName, "API", version, randomID); successMap = newMS.addValuesToNewModel(type); @@ -180,8 +178,7 @@ public class ImportService { } PolicyLogger.info("Request from API to import new Optimization Service Model"); try (Writer writer = new BufferedWriter(new OutputStreamWriter( - new FileOutputStream(extractDir + File.separator + randomID + type), - "utf-8"))) { + new FileOutputStream(extractDir + File.separator + randomID + type), "utf-8"))) { writer.write(yml); } catch (IOException e) { logger.error(e); @@ -189,8 +186,7 @@ public class ImportService { return; } - newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", - version, randomID); + newOOF = new CreateNewOptimizationModel(fileName, serviceName, "API Import Service", version, randomID); successMap = newOOF.addValuesToNewModel(); if (successMap.containsKey(successMessage)) { successMap.clear(); diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java index 0a539dcbb..594112636 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/service/MetricService.java @@ -21,10 +21,13 @@ package org.onap.policy.pap.xacml.rest.service; import com.att.research.xacml.api.pap.PDPPolicy; + import java.util.HashSet; import java.util.List; import java.util.Set; + import javax.servlet.http.HttpServletResponse; + import org.json.JSONObject; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java index f411e7d98..2b0bc3a4b 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/AbstractPolicyCreation.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,17 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.util; +import com.att.research.xacml.util.XACMLProperties; +import com.google.common.base.Joiner; import java.util.UUID; import org.onap.policy.rest.XACMLRestProperties; import org.springframework.stereotype.Component; -import com.att.research.xacml.util.XACMLProperties; -import com.google.common.base.Joiner; - @Component public abstract class AbstractPolicyCreation { @@ -36,63 +36,64 @@ public abstract class AbstractPolicyCreation { } public String newPolicyID() { - return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null: "urn"), + return Joiner.on(':').skipNulls().join((getDomain().startsWith("urn") ? null : "urn"), getDomain().replaceAll("[/\\\\.]", ":"), "xacml", "policy", "id", UUID.randomUUID()); } public String convertDate(String dateTTL) { String formateDate = null; - if(dateTTL.contains("/")){ + if (dateTTL.contains("/")) { formateDate = dateTTL.replace("/", "-"); - }else { + } else { formateDate = dateTTL; } return formateDate; } - - - public void updatePolicyCreationToDatabase(){ + public void updatePolicyCreationToDatabase() { // Add it into our tree -/* Path finalPolicyPath = null; - finalPolicyPath = Paths.get(successMap.get("success")); - PolicyElasticSearchController controller = new PolicyElasticSearchController(); - controller.updateElk(finalPolicyPath.toString()); - File file = finalPolicyPath.toFile(); - if(file != null){ - String policyName = file.toString(); - String removePath = policyName.substring(policyName.indexOf("repository")+11); - String removeXml = removePath.replace(".xml", ""); - String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); - List<Object> policyVersionList = commonClassDao.getDataById(PolicyVersion.class, "policyName", removeExtension); - if (policyVersionList.size() > 0) { - for(int i = 0; i < policyVersionList.size(); i++) { - PolicyVersion entityItem = (PolicyVersion) policyVersionList.get(i); - if(entityItem.getPolicyName().equals(removeExtension)){ - version = entityItem.getHigherVersion() +1; - entityItem.setActiveVersion(version); - entityItem.setHigherVersion(version); - entityItem.setModifiedBy(userId); - commonClassDao.update(entityItem); - if(policyData.isEditPolicy){ - PolicyNotificationMail email = new PolicyNotificationMail(); - String mode = "EditPolicy"; - String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + ".xml"; - email.sendMail(entityItem, policyNameForEmail, mode, commonClassDao); - } - } - } - }else{ - PolicyVersion entityItem = new PolicyVersion(); - entityItem.setActiveVersion(version); - entityItem.setHigherVersion(version); - entityItem.setPolicyName(removeExtension); - entityItem.setCreatedBy(userId); - entityItem.setModifiedBy(userId); - commonClassDao.save(entityItem); - } - }*/ + /* + * Path finalPolicyPath = null; + * finalPolicyPath = Paths.get(successMap.get("success")); + * PolicyElasticSearchController controller = new PolicyElasticSearchController(); + * controller.updateElk(finalPolicyPath.toString()); + * File file = finalPolicyPath.toFile(); + * if(file != null){ + * String policyName = file.toString(); + * String removePath = policyName.substring(policyName.indexOf("repository")+11); + * String removeXml = removePath.replace(".xml", ""); + * String removeExtension = removeXml.substring(0, removeXml.indexOf(".")); + * List<Object> policyVersionList = commonClassDao.getDataById(PolicyVersion.class, "policyName", + * removeExtension); + * if (policyVersionList.size() > 0) { + * for(int i = 0; i < policyVersionList.size(); i++) { + * PolicyVersion entityItem = (PolicyVersion) policyVersionList.get(i); + * if(entityItem.getPolicyName().equals(removeExtension)){ + * version = entityItem.getHigherVersion() +1; + * entityItem.setActiveVersion(version); + * entityItem.setHigherVersion(version); + * entityItem.setModifiedBy(userId); + * commonClassDao.update(entityItem); + * if(policyData.isEditPolicy){ + * PolicyNotificationMail email = new PolicyNotificationMail(); + * String mode = "EditPolicy"; + * String policyNameForEmail = policyData.getDomainDir() + File.separator + policyData.getOldPolicyFileName() + + * ".xml"; + * email.sendMail(entityItem, policyNameForEmail, mode, commonClassDao); + * } + * } + * } + * }else{ + * PolicyVersion entityItem = new PolicyVersion(); + * entityItem.setActiveVersion(version); + * entityItem.setHigherVersion(version); + * entityItem.setPolicyName(removeExtension); + * entityItem.setCreatedBy(userId); + * entityItem.setModifiedBy(userId); + * commonClassDao.save(entityItem); + * } + * } + */ } - } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java index e88efa931..ec27e0304 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/DictionaryUtils.java @@ -23,14 +23,17 @@ package org.onap.policy.pap.xacml.rest.util; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; + import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONObject; @@ -80,8 +83,7 @@ public class DictionaryUtils { } public boolean isRequestFromAPI(HttpServletRequest request) { - return request.getParameter(apiflag) != null - && "api".equalsIgnoreCase(request.getParameter(apiflag)); + return request.getParameter(apiflag) != null && "api".equalsIgnoreCase(request.getParameter(apiflag)); } public String appendKey(List<Object> objects, String key1, String appendValue) { @@ -134,8 +136,7 @@ public class DictionaryUtils { } public Category getCategory() { - return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource") - .get(0); + return (Category) commonClassDao.getDataById(Category.class, "shortName", "resource").get(0); } public ModelAndView getResultForApi(String inResponseString) { @@ -148,8 +149,7 @@ public class DictionaryUtils { return result; } - public void setResponseData(HttpServletResponse response, String key, String responseString) - throws IOException { + public void setResponseData(HttpServletResponse response, String key, String responseString) throws IOException { response.setCharacterEncoding(utf8); response.setContentType(applicationJsonContentType); @@ -166,13 +166,11 @@ public class DictionaryUtils { } @SuppressWarnings("rawtypes") - public void getDataByEntity(HttpServletResponse response, String key, String value, - Class className) { + public void getDataByEntity(HttpServletResponse response, String key, String value, Class className) { try { Map<String, Object> model = new HashMap<>(); ObjectMapper mapper = new ObjectMapper(); - model.put(key, - mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); + model.put(key, mapper.writeValueAsString(commonClassDao.getDataByColumn(className, value))); JsonMessage msg = new JsonMessage(mapper.writeValueAsString(model)); JSONObject j = new JSONObject(msg); response.getWriter().write(j.toString()); @@ -206,8 +204,7 @@ public class DictionaryUtils { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); - commonClassDao - .delete(mapper.readValue(root.get("data").toString(), className)); + commonClassDao.delete(mapper.readValue(root.get("data").toString(), className)); String responseString = mapper.writeValueAsString(commonClassDao.getData(className)); setResponseData(response, key, responseString); } catch (Exception e) { diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java index cb9abb9db..efb8287f0 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JPAUtils.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.util; import java.util.List; + import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.XacmlAdminAuthorization; @@ -41,7 +42,6 @@ public class JPAUtils { JPAUtils.commonClassDao = commonClassDao; } - /** * Get an instance of a JPAUtils. It creates one if it does not exist. Only one instance is allowed * to be created per server. diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java index 6ea0c79ee..cafeb0c92 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/rest/util/JsonMessage.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -25,17 +25,19 @@ public class JsonMessage { private String data; private String data2; private String data3; + public JsonMessage(String data) { super(); this.data = data; } - public JsonMessage(String data,String data2) { + + public JsonMessage(String data, String data2) { super(); this.data = data; this.data2 = data2; } - public JsonMessage(String data,String data2,String data3) { + public JsonMessage(String data, String data2, String data3) { super(); this.data = data; this.data2 = data2; @@ -49,19 +51,21 @@ public class JsonMessage { public void setData(String data) { this.data = data; } + public String getData2() { return data2; } + public void setData2(String data2) { this.data2 = data2; } + public String getData3() { return data3; } + public void setData3(String data3) { this.data3 = data3; } - } - diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java index 10cc81549..ff849435e 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/AuthenticationService.java @@ -21,9 +21,11 @@ package org.onap.policy.pap.xacml.restAuth; import com.att.research.xacml.util.XACMLProperties; + import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.StringTokenizer; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.rest.XACMLRestProperties; diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java index 181dd0910..ab1576715 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/CheckPDP.java @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.restAuth; import com.att.research.xacml.api.pap.PAPException; + import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; @@ -37,6 +38,7 @@ import java.util.HashMap; import java.util.List; import java.util.Objects; import java.util.Properties; + import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; import org.onap.policy.common.logging.flexlogger.FlexLogger; @@ -73,19 +75,20 @@ public class CheckPDP { String pdpFile = XACMLPapServlet.getPDPFile(); if (pdpFile == null) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "PDP File name is undefined"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"PDP File name not Valid : " + pdpFile); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "PDP File name not Valid : " + pdpFile); } if (pdpPath == null) { pdpPath = Paths.get(pdpFile); if (Files.notExists(pdpPath)) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "File doesn't exist in the specified Path"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"File doesn't exist in the specified Path : "+ pdpPath.toString()); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + + "File doesn't exist in the specified Path : " + pdpPath.toString()); } if (pdpPath.toString().endsWith(".properties")) { readProps(); } else { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR + "Not a .properties file"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Not a .properties file"); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Not a .properties file"); } } // Check if File is updated recently @@ -98,7 +101,7 @@ public class CheckPDP { } } - @SuppressWarnings({ "rawtypes", "unchecked" }) + @SuppressWarnings({"rawtypes", "unchecked"}) private static void readProps() throws PAPException { InputStream in; pdpProp = new Properties(); @@ -137,45 +140,47 @@ public class CheckPDP { } if (pdpMap == null || pdpMap.isEmpty()) { logger.debug(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); - throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR +"Cannot Proceed without PDP_URLs"); + throw new PAPException(XACMLErrorConstants.ERROR_SYSTEM_ERROR + "Cannot Proceed without PDP_URLs"); } } - private static void readPDPParam(String pdpVal) throws PAPException{ - if(pdpVal.contains(",")){ + private static void readPDPParam(String pdpVal) throws PAPException { + if (pdpVal.contains(",")) { List<String> pdpValues = new ArrayList<>(Arrays.asList(pdpVal.split("\\s*,\\s*"))); - if(pdpValues.size()==3){ + if (pdpValues.size() == 3) { // 1:2 will be UserID:Password String userID = pdpValues.get(1); String pass = PeCryptoUtils.decrypt(pdpValues.get(2)); Base64.Encoder encoder = Base64.getEncoder(); // 0 - PDPURL - pdpMap.put(pdpValues.get(0), encoder.encodeToString((userID+":"+pass).getBytes(StandardCharsets.UTF_8))); - }else{ + pdpMap.put(pdpValues.get(0), + encoder.encodeToString((userID + ":" + pass).getBytes(StandardCharsets.UTF_8))); + } else { PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request"); - throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); + throw new PAPException( + XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request. " + pdpValues); } - }else{ + } else { PolicyLogger.error(MessageCodes.ERROR_PERMISSIONS + "No Credentials to send Request: " + pdpVal); - throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS +"No enough Credentials to send Request."); + throw new PAPException(XACMLErrorConstants.ERROR_PERMISSIONS + "No enough Credentials to send Request."); } } - public static String getEncoding(String pdpID){ + public static String getEncoding(String pdpID) { try { readFile(); } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exeption reading Properties file"); } String encoding = null; - if(pdpMap!=null && (!pdpMap.isEmpty())){ - try{ + if (pdpMap != null && (!pdpMap.isEmpty())) { + try { encoding = pdpMap.get(pdpID); - } catch(Exception e){ + } catch (Exception e) { PolicyLogger.error(MessageCodes.ERROR_SYSTEM_ERROR, e, "CheckPDP", "Exception encoding"); } return encoding; - }else{ + } else { return null; } } diff --git a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java index 94cd9c798..323b89a01 100644 --- a/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java +++ b/ONAP-PAP-REST/src/main/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilter.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -41,13 +41,12 @@ import org.apache.commons.logging.LogFactory; @WebFilter("/*") public class PAPAuthenticationFilter implements Filter { - private static final Log logger = LogFactory.getLog(PAPAuthenticationFilter.class); + private static final Log logger = LogFactory.getLog(PAPAuthenticationFilter.class); public static final String AUTHENTICATION_HEADER = "Authorization"; @Override - public void doFilter(ServletRequest request, ServletResponse response, - FilterChain filter) throws IOException, ServletException { - + public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) + throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpServletRequest = (HttpServletRequest) request; @@ -57,7 +56,7 @@ public class PAPAuthenticationFilter implements Filter { logger.info("Request URI: " + url); - //getting authentication credentials + // getting authentication credentials authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER); // Check Authentication credentials @@ -65,17 +64,17 @@ public class PAPAuthenticationFilter implements Filter { boolean authenticationStatus = authenticationService.authenticate(authCredentials); if (authenticationStatus) { - //indicates the request comes from Traditional Admin Console or PolicyEngineAPI - if ("/pap/".equals(url)){ + // indicates the request comes from Traditional Admin Console or PolicyEngineAPI + if ("/pap/".equals(url)) { logger.info("Request comes from Traditional Admin Console or PolicyEngineAPI"); - //forward request to the XACMLPAPServlet if authenticated + // forward request to the XACMLPAPServlet if authenticated request.getRequestDispatcher("/pap/pap/").forward(request, response); - }else if (url.startsWith("/pap/onap/") && response instanceof HttpServletResponse){ - //indicates the request comes from the ONAP Portal onap-sdk-app - HttpServletResponse alteredResponse = ((HttpServletResponse)response); + } else if (url.startsWith("/pap/onap/") && response instanceof HttpServletResponse) { + // indicates the request comes from the ONAP Portal onap-sdk-app + HttpServletResponse alteredResponse = ((HttpServletResponse) response); addCorsHeader(alteredResponse); logger.info("Request comes from Onap Portal"); - //Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path + // Spring dispatcher servlet is at the end of the filter chain at /pap/onap/ path filter.doFilter(request, response); } } else { @@ -88,22 +87,23 @@ public class PAPAuthenticationFilter implements Filter { } } - //method to add CorsHeaders for onap portal rest call + // method to add CorsHeaders for onap portal rest call private void addCorsHeader(HttpServletResponse response) { logger.info("Adding Cors Response Headers!!!"); response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, HEAD"); - response.addHeader("Access-Control-Allow-Headers", "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept"); - response.addHeader("Access-Control-Max-Age", "1728000"); + response.addHeader("Access-Control-Allow-Headers", + "X-PINGOTHER, Origin, X-Requested-With, Content-Type, Accept"); + response.addHeader("Access-Control-Max-Age", "1728000"); } @Override public void destroy() { - //Empty + // Empty } @Override public void init(FilterConfig arg0) throws ServletException { - //Empty + // Empty } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java index 9fded580c..b6b674dc7 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/ia/DbAuditCompareEntriesTest.java @@ -86,7 +86,7 @@ public class DbAuditCompareEntriesTest { persistenceUnit = "testPapPU"; resourceName = "siteA.pap1"; - //Clean the iaTest DB table for IntegrityAuditEntity entries + // Clean the iaTest DB table for IntegrityAuditEntity entries cleanDb(persistenceUnit, properties); logger.info("setUp: Exiting"); @@ -95,11 +95,11 @@ public class DbAuditCompareEntriesTest { @After public void tearDown() throws Exception { logger.info("tearDown: Entering"); - //nothing to do + // nothing to do logger.info("tearDown: Exiting"); } - public void cleanDb(String persistenceUnit, Properties properties){ + public void cleanDb(String persistenceUnit, Properties properties) { logger.debug("cleanDb: enter"); EntityManagerFactory emf = Persistence.createEntityManagerFactory(persistenceUnit, properties); @@ -119,7 +119,6 @@ public class DbAuditCompareEntriesTest { logger.debug("cleanDb: exit"); } - /* * Tests that a comparison between hashsets is successful if * the entries match @@ -128,20 +127,18 @@ public class DbAuditCompareEntriesTest { public void runAllTests() throws Exception { logger.info("runAllTests: Entering"); - testIntegrityAuditEntity(); testBackupMonitorEntity(); testStateManagementEntity(); testForwardProgressEntity(); testResourceRegistrationEntity(); - //clean up the IntegrityAuditEntity table + // clean up the IntegrityAuditEntity table cleanDb(persistenceUnit, properties); logger.info("runAllTests: Exit"); } - public void testIntegrityAuditEntity() throws Exception { logger.info("testIntegrityAuditEntity: Entering"); @@ -149,10 +146,10 @@ public class DbAuditCompareEntriesTest { DbAudit dbAudit = new DbAudit(dbDAO); String className = null; - //There is only one entry IntegrityAuditEntity, but we will check anyway + // There is only one entry IntegrityAuditEntity, but we will check anyway Set<String> classNameSet = dbDAO.getPersistenceClassNames(); - for(String c : classNameSet){ - if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")){ + for (String c : classNameSet) { + if (c.equals("org.onap.policy.common.ia.jpa.IntegrityAuditEntity")) { className = c; } } @@ -231,7 +228,6 @@ public class DbAuditCompareEntriesTest { // Two entries with the same field values - entry1.setFlag("flag1"); entry1.setResourceNodeName("node1"); entry1.setResourceName("resourceName"); @@ -248,17 +244,14 @@ public class DbAuditCompareEntriesTest { Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - // Assert that there are no mismatches returned assertTrue(result.isEmpty()); - - /* ************************************ + /* + * ************************************ * Now test with a mis-matched entry - * ************************************/ - - + ************************************/ // Change a field on entry2 @@ -272,8 +265,7 @@ public class DbAuditCompareEntriesTest { result = dbAudit.compareEntries(myEntries, theirEntries); - - //Assert that there was one mismatch + // Assert that there was one mismatch assertEquals(1, result.size()); logger.info("testBackupMonitorEntity: Exit"); @@ -308,17 +300,14 @@ public class DbAuditCompareEntriesTest { Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - // Assert that there are no mismatches returned assertTrue(result.isEmpty()); - - /* ************************************ + /* + * ************************************ * Now test with a mis-matched entry - * ************************************/ - - + ************************************/ // Change a field on entry2 @@ -332,8 +321,7 @@ public class DbAuditCompareEntriesTest { result = dbAudit.compareEntries(myEntries, theirEntries); - - //Assert that there was one mismatch + // Assert that there was one mismatch assertEquals(1, result.size()); logger.info("testStateManagementEntity: Exit"); @@ -365,15 +353,14 @@ public class DbAuditCompareEntriesTest { Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - // Assert that there are no mismatches returned assertTrue(result.isEmpty()); - - /* ************************************ + /* + * ************************************ * Now test with a mis-matched entry - * ************************************/ + ************************************/ // Change a field on entry2 @@ -387,8 +374,7 @@ public class DbAuditCompareEntriesTest { result = dbAudit.compareEntries(myEntries, theirEntries); - - //Assert that there was one mismatch + // Assert that there was one mismatch assertEquals(1, result.size()); logger.info("testForwardProgressEntity: Exit"); @@ -422,15 +408,14 @@ public class DbAuditCompareEntriesTest { Set<Object> result = dbAudit.compareEntries(myEntries, theirEntries); - // Assert that there are no mismatches returned assertTrue(result.isEmpty()); - - /* ************************************ + /* + * ************************************ * Now test with a mis-matched entry - * ************************************/ + ************************************/ // Change a field on entry2 @@ -444,10 +429,9 @@ public class DbAuditCompareEntriesTest { result = dbAudit.compareEntries(myEntries, theirEntries); - - //Assert that there was one mismatch + // Assert that there was one mismatch assertEquals(1, result.size()); logger.info("testResourceRegistrationEntity: Exit"); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java index 5a8e20b26..99902012b 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/UpdateOthersPAPSTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.test; import static org.junit.Assert.assertTrue; @@ -60,9 +61,9 @@ public class UpdateOthersPAPSTest { public void setUp() throws Exception { logger.info("setUp: Entering"); commonClassDao = mock(CommonClassDao.class); - - request = mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + + request = mock(HttpServletRequest.class); + response = new MockHttpServletResponse(); List<Object> data = new ArrayList<>(); PolicyDBDaoEntity entity = new PolicyDBDaoEntity(); entity.setPolicyDBDaoUrl("http://localhost:8070/pap"); @@ -76,12 +77,12 @@ public class UpdateOthersPAPSTest { data.add(entity); data.add(entity1); - System.setProperty("xacml.rest.pap.url","http://localhost:8070/pap"); + System.setProperty("xacml.rest.pap.url", "http://localhost:8070/pap"); when(commonClassDao.getData(PolicyDBDaoEntity.class)).thenReturn(data); } @Test - public void testNotifyOthersPAPsToUpdateConfigurations(){ + public void testNotifyOthersPAPsToUpdateConfigurations() { UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS(); UpdateOthersPAPS.setCommonClassDao(commonClassDao); when(request.getParameter("action")).thenReturn("rename"); @@ -98,7 +99,7 @@ public class UpdateOthersPAPSTest { @PrepareForTest({Policy.class}) @Test - public void testUpdateConfiguration() throws Exception{ + public void testUpdateConfiguration() throws Exception { UpdateOthersPAPS updateOtherPaps = new UpdateOthersPAPS(); UpdateObjectData data = new UpdateObjectData(); PowerMockito.mockStatic(Policy.class); @@ -109,7 +110,8 @@ public class UpdateOthersPAPSTest { when(Policy.getActionHome()).thenReturn("test"); File mockedFile = Mockito.mock(File.class); Mockito.when(mockedFile.exists()).thenReturn(true); - PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(Matchers.anyString()).thenReturn(mockedFile); + PowerMockito.whenNew(File.class).withParameterTypes(String.class).withArguments(Matchers.anyString()) + .thenReturn(mockedFile); updateOtherPaps.updateConfiguration(data, response); assertTrue(response.getStatus() == 200); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java index fd0c157fe..ebfbf551f 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/test/XACMLPAPTest.java @@ -24,7 +24,9 @@ package org.onap.policy.pap.test; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.when; + import com.mockrunner.mock.web.MockServletInputStream; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -36,11 +38,13 @@ import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; + import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; @@ -79,7 +83,6 @@ import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.mock.web.MockServletConfig; import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder; - public class XACMLPAPTest { private static final Log logger = LogFactory.getLog(XACMLPAPTest.class); @@ -93,10 +96,6 @@ public class XACMLPAPTest { private static SessionFactory sessionFactory; private static CommonClassDao commonClassDao; - private static final String DEFAULT_DB_DRIVER = "org.h2.Driver"; - private static final String DEFAULT_DB_USER = "sa"; - private static final String DEFAULT_DB_PWD = ""; - @BeforeClass public static void beforeClassSetup() throws ServletException { sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("xacmlpaptest"); @@ -336,7 +335,6 @@ public class XACMLPAPTest { Mockito.verify(httpServletResponse).addHeader("operation", "create"); } - @Test public void testDecisonBLGuardPolicy() throws IOException, ServletException, SQLException { httpServletRequest = Mockito.mock(HttpServletRequest.class); @@ -449,7 +447,6 @@ public class XACMLPAPTest { Mockito.verify(httpServletResponse).addHeader("operation", "create"); } - private void setPolicyCreation() { CommonClassDao commonClassDao = Mockito.mock(CommonClassDao.class); PolicyCreation.setCommonClassDao(commonClassDao); @@ -698,7 +695,6 @@ public class XACMLPAPTest { // Verify Mockito.verify(httpServletResponse).setStatus(HttpServletResponse.SC_OK); - httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = Mockito.mock(MockHttpServletResponse.class); json = "{\"dictionaryFields\":{\"attributeName\":\"TestMMrestAPI1\",\"type\":\"REST\",\"url\":\"testsomeurl" diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java index 49120a0d9..195e6208d 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/ConsoleAndApiServiceTest.java @@ -26,6 +26,7 @@ import static org.mockito.Mockito.when; import com.att.research.xacml.util.XACMLProperties; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -34,10 +35,13 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.io.IOUtils; import org.hibernate.SessionFactory; import org.junit.Before; @@ -119,7 +123,6 @@ public class ConsoleAndApiServiceTest { pap.init(servletConfig); } - /** * Sets the up. * @@ -228,7 +231,6 @@ public class ConsoleAndApiServiceTest { consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP5, logContext, stdEngine); assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); - Mockito.when(httpServletRequest.getParameter(GROUP_DESCRIPTION)).thenReturn(null); Mockito.when(httpServletRequest.getParameter(PDP_ID)).thenReturn("http://localhost:4344/pdp/"); Mockito.when(httpServletRequest.getMethod()).thenReturn(PUT); @@ -240,7 +242,6 @@ public class ConsoleAndApiServiceTest { consoleAndApi.doAcPut(httpServletRequest, httpServletResponse, TESTGRP5, logContext, stdEngine); assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); - httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = new MockHttpServletResponse(); Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); @@ -252,7 +253,6 @@ public class ConsoleAndApiServiceTest { consoleAndApi.doAcPost(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine); assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); - httpServletRequest = Mockito.mock(HttpServletRequest.class); httpServletResponse = new MockHttpServletResponse(); Mockito.when(httpServletRequest.getHeader(ENVIRONMENT_HEADER)).thenReturn(DEVL); @@ -264,7 +264,6 @@ public class ConsoleAndApiServiceTest { consoleAndApi.doAcDelete(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine); assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus()); - } @Test diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java index dfadf8e81..2815328a8 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/PAPRestConfigTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest; import static org.junit.Assert.assertEquals; + import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; import org.hibernate.SessionFactory; import org.junit.Test; @@ -45,7 +46,9 @@ public class PAPRestConfigTest { @Test public void testInit() { String driver = "org.mariadb.jdbc.Driver"; - String url = "jdbc:mariadb://localhost:3306/onap_sdk?connectTimeout=30000&socketTimeout=60000&log=true&sessionVariables=max_statement_time=30"; + String url = + "jdbc:mariadb://localhost:3306/onap_sdk?connectTimeout=30000&socketTimeout=60000&log=" + + "true&sessionVariables=max_statement_time=30"; String user = "policy_user"; String password = "policy_user"; @@ -58,7 +61,7 @@ public class PAPRestConfigTest { assertEquals(PAPRestConfig.getDbPassword(), password); // Test hibernate - BasicDataSource source = (BasicDataSource)config.getDataSource(); + BasicDataSource source = (BasicDataSource) config.getDataSource(); assertEquals(source.getDriverClassName(), driver); assertEquals(source.getUrl(), url); assertEquals(source.getUsername(), user); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java index 32d7dedd3..22f657249 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/WebConfigTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -21,13 +21,15 @@ package org.onap.policy.pap.xacml.rest; import static org.junit.Assert.fail; + import javax.servlet.ServletContext; import javax.servlet.ServletException; + import org.junit.Test; import org.mockito.Mockito; public class WebConfigTest { - @Test(expected=NullPointerException.class) + @Test(expected = NullPointerException.class) public void testNegativeStartup() throws ServletException { WebConfig init = new WebConfig(); ServletContext container = Mockito.mock(ServletContext.class); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java index 36d40278b..8e93ee476 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/XACMLPapServletTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -22,6 +22,7 @@ package org.onap.policy.pap.xacml.rest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; + import org.junit.Test; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; @@ -40,10 +41,10 @@ public class XACMLPapServletTest { assertNotNull(XACMLPapServlet.getActionHome()); assertEquals(XACMLPapServlet.getPersistenceUnit(), "XACML-PAP-REST"); - //assertNull(XACMLPapServlet.getEmf()); - //assertNull(XACMLPapServlet.getPDPFile()); - //assertNull(XACMLPapServlet.getPAPEngine()); - //assertNull(servlet.getIa()); + // assertNull(XACMLPapServlet.getEmf()); + // assertNull(XACMLPapServlet.getPDPFile()); + // assertNull(XACMLPapServlet.getPAPEngine()); + // assertNull(servlet.getIa()); XACMLPapServlet.setPapDbDriver(testVal); assertEquals(XACMLPapServlet.getPapDbDriver(), testVal); @@ -60,9 +61,8 @@ public class XACMLPapServletTest { // Restore the original system property if (oldProperty != null) { - System.setProperty(systemKey, oldProperty); - } - else { + System.setProperty(systemKey, oldProperty); + } else { System.clearProperty(systemKey); } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java index 841ba28fc..1b1564cf9 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/SearchDataTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.adapters; import static org.junit.Assert.*; @@ -25,9 +26,8 @@ import org.junit.Test; public class SearchDataTest { - @Test - public void testSearchData(){ + public void testSearchData() { String data = "Test"; SearchData searchData = new SearchData(); searchData.setQuery(data); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java index 094994e41..00649c5e2 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/adapters/UpdateObjectDataTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.adapters; import static org.junit.Assert.assertTrue; @@ -26,7 +27,7 @@ import org.junit.Test; public class UpdateObjectDataTest { @Test - public void testClosedLoopFaultTrapDatas(){ + public void testClosedLoopFaultTrapDatas() { UpdateObjectData updateObject = new UpdateObjectData(); updateObject.setAction("Rename"); assertTrue("Rename".equals(updateObject.getAction())); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java index b80eaed89..6f4e09775 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ActionPolicyTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,15 +19,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.*; import static org.mockito.Mockito.when; + +import com.att.research.xacml.util.XACMLProperties; + import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; + import org.junit.After; import org.junit.Before; import org.junit.Test; @@ -35,8 +40,6 @@ import org.mockito.Mockito; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import com.att.research.xacml.util.XACMLProperties; - public class ActionPolicyTest { @@ -55,8 +58,7 @@ public class ActionPolicyTest { @Before public void setUp() throws Exception { logger.info("setUp: Entering"); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, - "src/test/resources/xacml.pap.properties"); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); dynamicRuleAlgorithmLabels.add("test"); dynamicRuleAlgorithmField1.add("testField1"); @@ -65,8 +67,7 @@ public class ActionPolicyTest { policyAdapter.setPolicyName("Test.Action_junitTest"); policyAdapter.setPolicyDescription("test"); - policyAdapter.setRuleCombiningAlgId( - "urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); + policyAdapter.setRuleCombiningAlgId("urn:oasis:names:tc:xacml:3.0:rule-combining-algorithm:permit-overrides"); policyAdapter.setPolicyType("Action"); policyAdapter.setEditPolicy(false); policyAdapter.setDomainDir("Test"); @@ -95,12 +96,6 @@ public class ActionPolicyTest { } /** - * @throws java.lang.Exception - */ - @After - public void tearDown() throws Exception {} - - /** * Test method for * {@link org.openecomp.policy.pap.xacml.rest.components.ActionPolicy#savePolicies()}. */ diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java index 39586ba1b..333d878ca 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/BRMSPolicyTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,11 +19,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; + import java.io.IOException; + import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java index 542d45e3e..75fa23605 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/ClosedLoopPolicyTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,19 +17,23 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; -import java.io.IOException; -import org.onap.policy.rest.adapter.PolicyRestAdapter; + import com.att.research.xacml.api.pap.PAPException; + +import java.io.IOException; import java.nio.charset.StandardCharsets; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.onap.policy.rest.adapter.PolicyRestAdapter; + public class ClosedLoopPolicyTest { @Rule public ExpectedException thrown = ExpectedException.none(); @@ -51,7 +55,7 @@ public class ClosedLoopPolicyTest { @Test public void testReadFile() throws IOException { thrown.expect(IOException.class); - String read = ClosedLoopPolicy.readFile("/foo", StandardCharsets.UTF_8); + ClosedLoopPolicy.readFile("/foo", StandardCharsets.UTF_8); fail("Expecting an exception."); } @@ -65,4 +69,4 @@ public class ClosedLoopPolicyTest { policy.prepareToSave(); assertEquals(policy.isPreparedToSave(), true); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java index ec9229c71..900d1227f 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/DecisionPolicyTest.java @@ -23,12 +23,15 @@ package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; + import com.att.research.xacml.util.XACMLProperties; + import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.UUID; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -61,7 +64,7 @@ public class DecisionPolicyTest { @Before public void setUp() throws Exception { logger.info("setUp: Entering"); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties"); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); policyAdapter.setPolicyName("Test.Decision_junitTest.1.xml"); policyAdapter.setPolicyDescription("testing"); @@ -71,10 +74,10 @@ public class DecisionPolicyTest { policyAdapter.setDomainDir("Test"); policyAdapter.setNewFileName("/src/test/resources/Test/client.properties"); policyAdapter.setHighestVersion(1); - policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID()); + policyAdapter.setPolicyID("urn:xacml:policy:id:" + UUID.randomUUID()); policyAdapter.setOnapName("MSO"); - //rainy day attributes + // rainy day attributes attributeMap.put("ServiceType", "S"); attributeMap.put("VNFType", "V"); attributeMap.put("BB_ID", "testBB"); @@ -119,7 +122,7 @@ public class DecisionPolicyTest { e.printStackTrace(); } - assertEquals(successMap.get("success"),"success"); + assertEquals(successMap.get("success"), "success"); } /** @@ -135,7 +138,7 @@ public class DecisionPolicyTest { try { response = component.prepareToSave(); } catch (Exception e) { - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); } assertTrue(response); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java index 7f3ebb3b4..4ddc8d057 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/FirewallConfigPolicyTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -17,15 +17,17 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.*; import static org.mockito.Mockito.when; +import com.att.research.xacml.util.XACMLProperties; + import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; - import java.util.Map; import java.util.UUID; @@ -38,9 +40,6 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.test.XACMLPAPTest; import org.onap.policy.rest.adapter.PolicyRestAdapter; -import com.att.research.xacml.util.XACMLProperties; - - public class FirewallConfigPolicyTest { private static Logger logger = FlexLogger.getLogger(FirewallConfigPolicyTest.class); @@ -56,7 +55,7 @@ public class FirewallConfigPolicyTest { @Before public void setUp() throws Exception { logger.info("setup: enter"); - System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME,"src/test/resources/xacml.pap.properties"); + System.setProperty(XACMLProperties.XACML_PROPERTIES_NAME, "src/test/resources/xacml.pap.properties"); policyAdapter.setPolicyName("FWjunitTest"); policyAdapter.setPolicyDescription("test"); @@ -68,7 +67,7 @@ public class FirewallConfigPolicyTest { policyAdapter.setNewFileName("Test.Config_FW_junitTest.1.xml"); policyAdapter.setHighestVersion(1); policyAdapter.setVersion(String.valueOf(1)); - policyAdapter.setPolicyID("urn:xacml:policy:id:"+UUID.randomUUID()); + policyAdapter.setPolicyID("urn:xacml:policy:id:" + UUID.randomUUID()); policyAdapter.setRuleID(""); policyAdapter.setConfigName("testname"); policyAdapter.setGuard("True"); @@ -106,7 +105,7 @@ public class FirewallConfigPolicyTest { when(mockFWConfig.savePolicies()).thenReturn(successMap); successMap = mockFWConfig.savePolicies(); } catch (Exception e) { - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); } } @@ -122,29 +121,74 @@ public class FirewallConfigPolicyTest { when(mockFWConfig.prepareToSave()).thenReturn(true); response = mockFWConfig.prepareToSave(); } catch (Exception e) { - logger.error("Exception Occured"+e); + logger.error("Exception Occured" + e); } assertTrue(response); } @Test - public void testUpdateJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ + public void testUpdateJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, + IllegalArgumentException, InvocationTargetException { FirewallConfigPolicy firewallConfigPolicy = new FirewallConfigPolicy(); - Method method = firewallConfigPolicy.getClass().getDeclaredMethod("updateFirewallDictionaryData", String.class , String.class); + Method method = firewallConfigPolicy.getClass().getDeclaredMethod("updateFirewallDictionaryData", String.class, + String.class); method.setAccessible(true); - String jsonBody= "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"test\",\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FWrule for Test source to Test destination\",\"enabled\":true,\"log\":true}]}"; - String prevJsonBody = "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicy1Config\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev\",\"vendorServiceId\":\"test\",\"vendorSpecificData\":{\"idMap\":[{\"Id\":\"cloudsite:dev1a\",\"vendorId\":\"deviceGroup:dev\"}]},\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Ssh service entry in service list\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"Test\",\"description\":\"Destination Test\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"Source TestServers for first testing\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerTot\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FW rule for HOHO source to CiscoVCE destination\",\"enabled\":true,\"log\":true}]}"; + String jsonBody = + "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":" + + "{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":" + + "\"SSH\",\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\"," + + "\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":" + + "[{\"name\":\"test\",\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":" + + "\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":" + + "\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\",\"value\":" + + "\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":" + + "\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":" + + "[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":" + + "[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":" + + "\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":" + + "\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":" + + "\"FWrule for Test source to Test destination\",\"enabled\":true,\"log\":true}]}"; + String prevJsonBody = + "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicy1Config\"," + + "\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev\"," + + "\"vendorServiceId\":\"test\",\"vendorSpecificData\":{\"idMap\":[{\"Id\":\"cloudsite:dev1a\"," + + "\"vendorId\":\"deviceGroup:dev\"}]},\"serviceGroups\":[{\"name\":\"SSH\",\"description\":" + + "\"Ssh service entry in service list\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\"," + + "\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"Test\",\"description\":" + + "\"Destination Test\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":" + + "\"TestServers\",\"description\":\"Source TestServers for first testing\",\"members\":[{\"type\":" + + "\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":" + + "\"FWRuleTestServerTot\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":" + + "[\"TrustedZoneTName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":" + + "[{\"type\":\"REFERENCE\",\"name\":\"TServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\"," + + "\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":" + + "\"SSH\"}],\"action\":\"accept\",\"description\":\"FW rule for HOHO source to CiscoVCE destination\"," + + "\"enabled\":true,\"log\":true}]}"; assertTrue((Boolean) method.invoke(firewallConfigPolicy, jsonBody, prevJsonBody)); } @Test - public void testInsertJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{ + public void testInsertJson() throws NoSuchMethodException, SecurityException, IllegalAccessException, + IllegalArgumentException, InvocationTargetException { FirewallConfigPolicy firewallConfigPolicy = new FirewallConfigPolicy(); Method method = firewallConfigPolicy.getClass().getDeclaredMethod("insertFirewallDicionaryData", String.class); method.setAccessible(true); - String jsonBody= "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":\"SSH\",\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\",\"transportProtocol\":\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"test\",\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]},{\"name\":\"TestServers\",\"description\":\"SourceTestServers for firsttesting\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\",\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\",\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":\"SSH\"}],\"action\":\"accept\",\"description\":\"FWrule for Test source to Test destination\",\"enabled\":true,\"log\":true}]}"; + String jsonBody = + "{\"serviceTypeId\":\"/v0/firewall/pan\",\"configName\":\"TestFwPolicyConfig\",\"deploymentOption\":" + + "{\"deployNow\":false},\"securityZoneId\":\"cloudsite:dev1a\",\"serviceGroups\":[{\"name\":\"SSH\"," + + "\"description\":\"Sshservice entry in servicelist\",\"type\":\"SERVICE\",\"transportProtocol\":" + + "\"tcp\",\"appProtocol\":null,\"ports\":\"22\"}],\"addressGroups\":[{\"name\":\"test\"," + + "\"description\":\"Destination\",\"members\":[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/12\"}]}," + + "{\"name\":\"TestServers\",\"description\":\"SourceTestServers for firsttesting\",\"members\":" + + "[{\"type\":\"SUBNET\",\"value\":\"127.0.0.1/23\"}]}],\"firewallRuleList\":[{\"position\":\"1\"," + + "\"ruleName\":\"FWRuleTestServerToTest\",\"fromZones\":[\"UntrustedZoneTestName\"],\"toZones\":" + + "[\"TrustedZoneTestName\"],\"negateSource\":false,\"negateDestination\":false,\"sourceList\":" + + "[{\"type\":\"REFERENCE\",\"name\":\"TestServers\"}],\"destinationList\":[{\"type\":\"REFERENCE\"," + + "\"name\":\"Test\"}],\"sourceServices\":[],\"destServices\":[{\"type\":\"REFERENCE\",\"name\":" + + "\"SSH\"}],\"action\":\"accept\",\"description\":\"FWrule for Test source to Test destination\"," + + "\"enabled\":true,\"log\":true}]}"; assertTrue((Boolean) method.invoke(firewallConfigPolicy, jsonBody)); } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java index 436ff7fc8..9efb187cd 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/HandleIncomingNotificationsTest.java @@ -22,10 +22,13 @@ package org.onap.policy.pap.xacml.rest.components; import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.IOException; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.io.IOUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java index f698bc0c0..bda31de21 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/MicroServicePolicyTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,15 +17,20 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; -import static org.mockito.Matchers.any; + +import java.io.File; +import java.util.Collections; + import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -36,8 +41,6 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.util.Collections; @RunWith(PowerMockRunner.class) public class MicroServicePolicyTest { @@ -104,7 +107,8 @@ public class MicroServicePolicyTest { // Test create methods String testFileName = "testFile.zip"; String testVal = "testVal"; - CreateNewMicroServiceModel model = new CreateNewMicroServiceModel(testFileName, testVal, testVal, testVal, testVal); + CreateNewMicroServiceModel model = + new CreateNewMicroServiceModel(testFileName, testVal, testVal, testVal, testVal); model.addValuesToNewModel(".xmi"); model.saveImportService(); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java index 25e94c1a2..9fc6add39 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/OptimizationConfigPolicyTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,15 +17,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; +import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.when; -import static org.mockito.Matchers.any; + +import java.io.File; +import java.util.Collections; + import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; @@ -36,8 +40,6 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -import java.io.File; -import java.util.Collections; @RunWith(PowerMockRunner.class) public class OptimizationConfigPolicyTest { @@ -98,7 +100,8 @@ public class OptimizationConfigPolicyTest { // Test create methods String testFileName = "testFile.zip"; String testVal = "testVal"; - CreateNewOptimizationModel model = new CreateNewOptimizationModel(testFileName, testVal, testVal, testVal, testVal); + CreateNewOptimizationModel model = + new CreateNewOptimizationModel(testFileName, testVal, testVal, testVal, testVal); model.addValuesToNewModel(); model.saveImportService(); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java index e4da430a5..80b546d11 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/components/PolicyDBDaoTest.java @@ -21,8 +21,10 @@ package org.onap.policy.pap.xacml.rest.components; import static org.junit.Assert.fail; + import com.att.research.xacml.api.pap.PAPException; import com.att.research.xacml.util.XACMLProperties; + import java.io.File; import java.io.IOException; import java.nio.file.Path; @@ -30,12 +32,12 @@ import java.nio.file.Paths; import java.util.Date; import java.util.List; import java.util.Properties; -import javax.persistence.EntityManager; -import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; import javax.persistence.PersistenceException; + import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; + import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.tomcat.dbcp.dbcp2.BasicDataSource; @@ -156,10 +158,9 @@ public class PolicyDBDaoTest { return sessionFac; } - private static void setUpAuditDb() { Properties properties = new Properties(); - properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver"); + properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER, "org.h2.Driver"); properties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest"); properties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa"); properties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""); @@ -340,7 +341,6 @@ public class PolicyDBDaoTest { session2.getTransaction().commit(); session2.close(); - // add a pdp to a group group = dbd.getNewTransaction(); try { @@ -379,7 +379,6 @@ public class PolicyDBDaoTest { session3.getTransaction().commit(); session3.close(); - group = dbd.getNewTransaction(); try { group.removePdpFromGroup("http://localhost:4344/pdp/", "testuser"); @@ -457,7 +456,6 @@ public class PolicyDBDaoTest { session5.getTransaction().commit(); session5.close(); - group = dbd.getNewTransaction(); try { OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), Paths.get("/")); @@ -497,7 +495,6 @@ public class PolicyDBDaoTest { session7.getTransaction().commit(); session7.close(); - group = dbd.getNewTransaction(); try { OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), Paths.get("/")); @@ -589,7 +586,6 @@ public class PolicyDBDaoTest { } Assert.assertFalse(t.isTransactionOpen()); - if (logger.isDebugEnabled()) { Date date = new java.util.Date(); logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n a = dbd.getNewTransaction() " @@ -639,8 +635,6 @@ public class PolicyDBDaoTest { Assert.assertTrue(b.isTransactionOpen()); b.close(); - - // Now let's test the transaction wait time timeout. Shorten the wait time to 1000 ms System.setProperty(XACMLRestProperties.PROP_PAP_TRANS_WAIT, "1000"); // And let's lengthen the transaction timeout to 5000 ms diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java index efb13b5a0..eccf13ba7 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ActionPolicyDictionaryControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -57,8 +58,8 @@ public class ActionPolicyDictionaryControllerTest { public void setUp() throws Exception { logger.info("setUp: Entering"); commonClassDao = Mockito.mock(CommonClassDao.class); - List<String> data = new ArrayList<>(); - List<Object> objectData = new ArrayList<>(); + List<String> data = new ArrayList<>(); + List<Object> objectData = new ArrayList<>(); data.add("Test"); UserInfo userInfo = new UserInfo(); @@ -71,9 +72,9 @@ public class ActionPolicyDictionaryControllerTest { actionData.setBody("Test"); assertTrue("Test".equals(actionData.getBody())); actionData.setCreatedDate(new Date()); - assertTrue(actionData.getCreatedDate()!= null); + assertTrue(actionData.getCreatedDate() != null); actionData.setModifiedDate(new Date()); - assertTrue(actionData.getModifiedDate()!= null); + assertTrue(actionData.getModifiedDate() != null); actionData.setHeader("Test"); assertTrue("Test".equals(actionData.getHeader())); actionData.setMethod("POST"); @@ -83,9 +84,9 @@ public class ActionPolicyDictionaryControllerTest { actionData.setUrl("http://test.com"); assertTrue("http://test.com".equals(actionData.getUrl())); actionData.setUserCreatedBy(userInfo); - assertTrue(actionData.getUserCreatedBy()!= null); + assertTrue(actionData.getUserCreatedBy() != null); actionData.setUserModifiedBy(userInfo); - assertTrue(actionData.getUserModifiedBy()!= null); + assertTrue(actionData.getUserModifiedBy() != null); objectData.add(actionData); when(commonClassDao.getDataByColumn(ActionPolicyDict.class, "attributeName")).thenReturn(data); @@ -95,7 +96,7 @@ public class ActionPolicyDictionaryControllerTest { controller = new ActionPolicyDictionaryController(); controller.setCommonClassDao(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); @@ -103,60 +104,78 @@ public class ActionPolicyDictionaryControllerTest { } @Test - public void testGetActionEntitybyName(){ + public void testGetActionEntitybyName() { controller.getActionEntitybyName(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetActionPolicyDictionaryEntityData(){ + public void testGetActionPolicyDictionaryEntityData() { controller.getActionPolicyDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSaveActionPolicyDictionary(){ - jsonString = "{\"actionPolicyDictionaryData\":{\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveActionPolicyDictionary() { + jsonString = + "{\"actionPolicyDictionaryData\":{\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":" + + "\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\"," + + "\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"}," + + "\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveActionPolicyDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateActionPolicyDictionary(){ - jsonString = "{\"actionPolicyDictionaryData\":{\"id\":1,\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateActionPolicyDictionary() { + jsonString = + "{\"actionPolicyDictionaryData\":{\"id\":1,\"attributeName\":\"Test\",\"body\":\"{}\",\"description\":" + + "\"test\",\"headers\":[{\"$$hashKey\":\"object:548\",\"id\":\"choice1\",\"number\":" + + "\"12\",\"option\":\"test\"}],\"method\":\"GET\",\"type\":\"REST\",\"url\":\"http://test.com\"}," + + "\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveActionPolicyDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveActionPolicyDictionary(){ - jsonString = "{\"data\":{\"$$hashKey\":\"uiGrid-003S\",\"attributeName\":\"Test\",\"body\":\"{}\",\"createdDate\":1518195117000,\"description\":\"test\",\"header\":\"test=12\",\"id\":1,\"method\":\"GET\",\"modifiedDate\":1518195489000,\"type\":\"REST\",\"url\":\"http://test.com\",\"userCreatedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"},\"userModifiedBy\":{\"userLoginId\":\"demo\",\"userName\":\"Demo\"}}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testRemoveActionPolicyDictionary() { + jsonString = + "{\"data\":{\"$$hashKey\":\"uiGrid-003S\",\"attributeName\":\"Test\",\"body\":\"{}\",\"createdDate\":" + + "1518195117000,\"description\":\"test\",\"header\":\"test=12\",\"id\":1,\"method\":\"GET\"," + + "\"modifiedDate\":1518195489000,\"type\":\"REST\",\"url\":\"http://test.com\",\"userCreatedBy\":" + + "{\"userLoginId\":\"demo\",\"userName\":\"Demo\"},\"userModifiedBy\":{\"userLoginId\":\"demo\"," + + "\"userName\":\"Demo\"}}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeActionPolicyDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("actionPolicyDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("actionPolicyDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java index d34e505ba..e68860e4d 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/BRMSDictionaryControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -61,14 +62,14 @@ public class BRMSDictionaryControllerTest { userInfo.setUserLoginId("testUserId"); userInfo.setUserName("John"); when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo); - List<String> brms = new ArrayList<String>(); + List<String> brms = new ArrayList<String>(); brms.add("BRMS-Model"); when(commonClassDao.getDataByColumn(BRMSParamTemplate.class, "name")).thenReturn(brms); doNothing().when(commonClassDao).delete(new BRMSParamTemplate()); doNothing().when(commonClassDao).save(new BRMSParamTemplate()); controller = new BRMSDictionaryController(); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); @@ -76,12 +77,13 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSParamDictionaryByNameEntityData(){ + public void testGetBRMSParamDictionaryByNameEntityData() { logger.info("testGetBRMSParamDictionaryByNameEntityData: Entering"); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSParamDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsParamDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -94,7 +96,8 @@ public class BRMSDictionaryControllerTest { logger.info("testGetBRMSParamDictionaryEntityData: Entering"); controller.getBRMSParamDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsParamDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -105,14 +108,16 @@ public class BRMSDictionaryControllerTest { @Test public void testSaveBRMSParamDictionary() { logger.info("testSaveBRMSParamDictionary: Entering"); - jsonString = "{\"brmsParamDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + jsonString = + "{\"brmsParamDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveBRMSParamDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryData")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsParamDictionaryData")); logger.info("response.getContentAsString(): " + response.getContentAsString()); - }catch(Exception e){ - logger.error("Exception"+ e); + } catch (Exception e) { + logger.error("Exception" + e); } logger.info("testSaveBRMSParamDictionary: exit"); } @@ -121,11 +126,12 @@ public class BRMSDictionaryControllerTest { public void testRemoveBRMSParamDictionary() { logger.info("testRemoveBRMSParamDictionary: Entering"); jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeBRMSParamDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsParamDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsParamDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); } @@ -133,12 +139,13 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSDependencyDictionaryByNameEntityData(){ + public void testGetBRMSDependencyDictionaryByNameEntityData() { logger.info("testGetBRMSDependencyDictionaryByNameEntityData: Entering"); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSDependencyDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -147,12 +154,13 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSDependencyDictionaryEntityData(){ + public void testGetBRMSDependencyDictionaryEntityData() { logger.info("testGetBRMSDependencyDictionaryEntityData: Entering"); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSDependencyDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -164,13 +172,16 @@ public class BRMSDictionaryControllerTest { @Test public void testSaveBRMSDependencyDictionary() { logger.info("testSaveBRMSDependencyDictionary: Entering"); - jsonString = "{\"brmsDependencyDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ - when(request.getReader()).thenReturn(br); - controller.saveBRMSDependencyDictionary(request, response); - logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryData")); - } catch (Exception e) { + jsonString = + "{\"brmsDependencyDictionaryData\": " + + "{\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { + when(request.getReader()).thenReturn(br); + controller.saveBRMSDependencyDictionary(request, response); + logger.info("response.getContentAsString(): " + response.getContentAsString()); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsDependencyDictionaryData")); + } catch (Exception e) { fail("Exception: " + e); } logger.info("testSaveBRMSDependencyDictionary: exit"); @@ -179,14 +190,15 @@ public class BRMSDictionaryControllerTest { @Test public void testRemoveBRMSDependencyDictionary() { logger.info("testRemoveBRMSDependencyDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeBRMSDependencyDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsDependencyDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); } @@ -194,13 +206,14 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSControllerDictionaryByNameEntityData(){ + public void testGetBRMSControllerDictionaryByNameEntityData() { logger.info("testGetBRMSControllerDictionaryByNameEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSControllerDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsControllerDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -209,13 +222,14 @@ public class BRMSDictionaryControllerTest { } @Test - public void testGetBRMSControllerDictionaryEntityData(){ + public void testGetBRMSControllerDictionaryEntityData() { logger.info("testGetBRMSControllerDictionaryEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); BRMSDictionaryController.setCommonClassDao(commonClassDao); controller.getBRMSControllerDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsControllerDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -227,14 +241,17 @@ public class BRMSDictionaryControllerTest { public void testSaveBRMSControllerDictionary() { logger.info("testSaveBRMSControllerDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); - jsonString = "{\"brmsControllerDictionaryData\": {\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + jsonString = + "{\"brmsControllerDictionaryData\": " + + "{\"ruleName\": \"test\",\"rule\": \"test\"},\"userid\": \"testName\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveBRMSControllerDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryData")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsControllerDictionaryData")); } catch (Exception e) { fail("Exception: " + e); } @@ -244,14 +261,15 @@ public class BRMSDictionaryControllerTest { @Test public void testRemoveBRMSControllerDictionary() { logger.info("testRemoveBRMSControllerDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); jsonString = "{\"data\": {\"ruleName\": \"test\",\"rule\": \"test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeBRMSControllerDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("brmsControllerDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("brmsControllerDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -259,4 +277,3 @@ public class BRMSDictionaryControllerTest { logger.info("testRemoveBRMSControllerDictionary: exit"); } } - diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java index f530b4c62..3472b0df5 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/ClosedLoopDictionaryControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -57,7 +58,7 @@ public class ClosedLoopDictionaryControllerTest { private ClosedLoopDictionaryController controller = null; private MockHttpServletResponse response = null; private UserInfo userInfo; - private List<String> data; + private List<String> data; @Before public void setUp() throws Exception { @@ -78,7 +79,7 @@ public class ClosedLoopDictionaryControllerTest { controller.setCommonClassDao(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); @@ -86,362 +87,404 @@ public class ClosedLoopDictionaryControllerTest { } @Test - public void testGetVSCLActionDictionaryByNameEntityData(){ + public void testGetVSCLActionDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(VSCLAction.class, "vsclaction")).thenReturn(data); controller.getVSCLActionDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVSCLActionDictionaryEntityData(){ + public void testGetVSCLActionDictionaryEntityData() { when(commonClassDao.getData(VSCLAction.class)).thenReturn(new ArrayList<>()); controller.getVSCLActionDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVNFTypeDictionaryByNameEntityData(){ + public void testGetVNFTypeDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(VNFType.class, "vnftype")).thenReturn(data); controller.getVNFTypeDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVNFTypeDictionaryEntityData(){ + public void testGetVNFTypeDictionaryEntityData() { when(commonClassDao.getData(VNFType.class)).thenReturn(new ArrayList<>()); controller.getVNFTypeDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPEPOptionsDictionaryByNameEntityData(){ + public void testGetPEPOptionsDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(PEPOptions.class, "pepName")).thenReturn(data); controller.getPEPOptionsDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPEPOptionsDictionaryEntityData(){ + public void testGetPEPOptionsDictionaryEntityData() { when(commonClassDao.getData(PEPOptions.class)).thenReturn(new ArrayList<>()); controller.getPEPOptionsDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVarbindDictionaryByNameEntityData(){ + public void testGetVarbindDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(VarbindDictionary.class, "varbindName")).thenReturn(data); controller.getVarbindDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetVarbindDictionaryEntityData(){ + public void testGetVarbindDictionaryEntityData() { when(commonClassDao.getData(VarbindDictionary.class)).thenReturn(new ArrayList<>()); controller.getVarbindDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetClosedLoopServiceDictionaryByNameEntityData(){ + public void testGetClosedLoopServiceDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(ClosedLoopD2Services.class, "serviceName")).thenReturn(data); controller.getClosedLoopServiceDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetClosedLoopServiceDictionaryEntityData(){ + public void testGetClosedLoopServiceDictionaryEntityData() { when(commonClassDao.getData(ClosedLoopD2Services.class)).thenReturn(new ArrayList<>()); controller.getClosedLoopServiceDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetClosedLoopSiteDictionaryByNameEntityData(){ + public void testGetClosedLoopSiteDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(ClosedLoopSite.class, "siteName")).thenReturn(data); controller.getClosedLoopSiteDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetClosedLoopSiteDictionaryEntityData(){ + public void testGetClosedLoopSiteDictionaryEntityData() { when(commonClassDao.getData(ClosedLoopSite.class)).thenReturn(new ArrayList<>()); controller.getClosedLoopSiteDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSaveVSCLAction(){ - jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"description\":\"test\",\"vsclaction\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveVSCLAction() { + jsonString = + "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"description\":\"test\",\"vsclaction\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVSCLAction(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateVSCLAction(){ - jsonString = "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateVSCLAction() { + jsonString = + "{\"userid\":\"demo\",\"vsclActionDictionaryData\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVSCLAction(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveVSCLAction(){ + public void testRemoveVSCLAction() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vsclaction\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeVSCLAction(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vsclActionDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vsclActionDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveVnfType(){ + public void testSaveVnfType() { jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"description\":\"test\",\"vnftype\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVnfType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateVnfType(){ - jsonString = "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateVnfType() { + jsonString = + "{\"userid\":\"demo\",\"vnfTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVnfType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveVnfType(){ + public void testRemoveVnfType() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"vnftype\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeVnfType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("vnfTypeDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("vnfTypeDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePEPOptions(){ - jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSavePEPOptions() { + jsonString = + "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePEPOptions(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePEPOptions(){ - jsonString = "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\",\"id\":1},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePEPOptions() { + jsonString = + "{\"pepOptionsDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\",\"id\":1},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePEPOptions(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePEPOptions(){ - jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testRemovePEPOptions() { + jsonString = + "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"pepName\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePEPOptions(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("pepOptionsDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("pepOptionsDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveServiceType(){ - jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"description\":\"test\",\"serviceName\":\"Test\",\"id\":1}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveServiceType() { + jsonString = + "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"description\":\"test\",\"serviceName\":\"Test\",\"id\":1}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveServiceType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateServiceType(){ - jsonString = "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateServiceType() { + jsonString = + "{\"userid\":\"demo\",\"closedLoopServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveServiceType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveServiceType(){ + public void testRemoveServiceType() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"serviceName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeServiceType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopServiceDictionaryData")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopServiceDictionaryData")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveSiteType(){ - jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"description\":\"test\",\"siteName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveSiteType() { + jsonString = + "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"description\":\"test\",\"siteName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveSiteType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateSiteType(){ - jsonString = "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateSiteType() { + jsonString = + "{\"userid\":\"demo\",\"closedLoopSiteDictionaryData\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveSiteType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveSiteType(){ + public void testRemoveSiteType() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"siteName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeSiteType(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("closedLoopSiteDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveVarbind(){ - jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"description\":\"test\",\"varbindName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveVarbind() { + jsonString = + "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"description\":\"test\",\"varbindName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVarbind(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateVarbind(){ - jsonString = "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateVarbind() { + jsonString = + "{\"userid\":\"demo\",\"varbindDictionaryData\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveVarbind(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveVarbind(){ + public void testRemoveVarbind() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"varbindName\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeVarbind(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("varbindDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("varbindDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java index 1334f96a0..30d6d52bc 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DecisionPolicyDictionaryControllerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,16 +19,19 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.io.BufferedReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; + import javax.servlet.http.HttpServletRequest; -import org.junit.After; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -39,8 +42,7 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.springframework.mock.web.MockHttpServletResponse; public class DecisionPolicyDictionaryControllerTest { - private static Logger logger = - FlexLogger.getLogger(DecisionPolicyDictionaryControllerTest.class); + private static Logger logger = FlexLogger.getLogger(DecisionPolicyDictionaryControllerTest.class); private static CommonClassDao commonClassDao; private String jsonString = null; private HttpServletRequest request = null; @@ -52,19 +54,18 @@ public class DecisionPolicyDictionaryControllerTest { commonClassDao = Mockito.mock(CommonClassDao.class); HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - jsonString = - "{\"attributeDictionaryDatas\": {\"error\": \"\",\"inprocess\": false,\"model\": " - + "{\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," - + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\"," - + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," - + "\"recursive\": false}," - + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," - + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," - + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," - + "\"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," - + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," - + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," - + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + jsonString = "{\"attributeDictionaryDatas\": {\"error\": \"\",\"inprocess\": false,\"model\": " + + "{\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," + + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\",\"version\": \"\"," + + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," + + "\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," + + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," + + "\"ecompName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); @@ -78,9 +79,6 @@ public class DecisionPolicyDictionaryControllerTest { logger.info("setUp: exit"); } - @After - public void tearDown() throws Exception {} - @Test public void testGetSettingsDictionaryByNameEntityData() { logger.info("testGetSettingsDictionaryByNameEntityData: Entering"); @@ -235,10 +233,9 @@ public class DecisionPolicyDictionaryControllerTest { try { // mock the getReader() call - jsonString = - "{\"rainyDayDictionaryData\":{\"bbid\":\"BB2\",\"workstep\":\"1\",\"userDataTypeValues\"" - + ":[{\"$$hashKey\":\"object:233\",\"treatment\":\"test1\"},{\"$$hashKey\":\"object:239\"," - + "\"treatment\":\"test2\"}]},\"userid\":\"mm117s\"}"; + jsonString = "{\"rainyDayDictionaryData\":{\"bbid\":\"BB2\",\"workstep\":\"1\",\"userDataTypeValues\"" + + ":[{\"$$hashKey\":\"object:233\",\"treatment\":\"test1\"},{\"$$hashKey\":\"object:239\"," + + "\"treatment\":\"test2\"}]},\"userid\":\"mm117s\"}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java index 0950b1cfd..f12299334 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DescriptiveDictionaryControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -53,7 +54,7 @@ public class DescriptiveDictionaryControllerTest { private DescriptiveDictionaryController controller = null; private MockHttpServletResponse response = null; private UserInfo userInfo; - private List<String> data; + private List<String> data; @Before public void setUp() throws Exception { @@ -74,15 +75,15 @@ public class DescriptiveDictionaryControllerTest { controller.setCommonClassDao(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); logger.info("setUp: exit"); } - public List<Object> testDescriptiveScope(){ - List<Object> objectData = new ArrayList<>(); + public List<Object> testDescriptiveScope() { + List<Object> objectData = new ArrayList<>(); DescriptiveScope data = new DescriptiveScope(); data.setId(1); @@ -94,75 +95,89 @@ public class DescriptiveDictionaryControllerTest { data.setSearch("Test"); assertTrue("Test".equals(data.getSearch())); data.setCreatedDate(new Date()); - assertTrue(data.getCreatedDate()!= null); + assertTrue(data.getCreatedDate() != null); data.setModifiedDate(new Date()); - assertTrue(data.getModifiedDate()!= null); + assertTrue(data.getModifiedDate() != null); data.setUserCreatedBy(userInfo); - assertTrue(data.getUserCreatedBy()!= null); + assertTrue(data.getUserCreatedBy() != null); data.setUserModifiedBy(userInfo); - assertTrue(data.getUserModifiedBy()!= null); + assertTrue(data.getUserModifiedBy() != null); objectData.add(data); return objectData; } @Test - public void testGetDescriptiveDictionaryByNameEntityData(){ + public void testGetDescriptiveDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(DescriptiveScope.class, "descriptiveScopeName")).thenReturn(data); controller.getDescriptiveDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetDescriptiveDictionaryEntityData(){ + public void testGetDescriptiveDictionaryEntityData() { when(commonClassDao.getData(DescriptiveScope.class)).thenReturn(testDescriptiveScope()); controller.getDescriptiveDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSaveDescriptiveDictionary(){ - jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"search\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveDescriptiveDictionary() { + jsonString = + "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":" + + "\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\"," + + "\"descriptiveScopeName\":\"Test\",\"search\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveDescriptiveDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateDescriptiveDictionary(){ - jsonString = "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdateDescriptiveDictionary() { + jsonString = + "{\"descriptiveScopeDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":" + + "\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\"," + + "\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveDescriptiveDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveDescriptiveDictionary(){ - jsonString = "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\",\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1,\"search\":\"Test\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testRemoveDescriptiveDictionary() { + jsonString = + "{\"data\":{\"attributes\":[{\"$$hashKey\":\"object:257\",\"id\":\"choice1\",\"number\":\"12\"," + + "\"option\":\"test\"}],\"description\":\"test\",\"descriptiveScopeName\":\"Test\",\"id\":1," + + "\"search\":\"Test\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeDescriptiveDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("descriptiveScopeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } -}
\ No newline at end of file +} diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java index 89be75f52..52b79b88f 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -18,7 +18,6 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -70,12 +69,12 @@ public class DictionaryControllerTest { commonClassDao = Mockito.mock(CommonClassDao.class); MicroServiceModels testData = new MicroServiceModels(); - testData.setVersion("1707.4.1.2-Junit"); + testData.setVersion("1707.4.1.2-Junit"); - //--- mock the getDataByColumn() call - List<String> microList = new ArrayList<String>(); + // --- mock the getDataByColumn() call + List<String> microList = new ArrayList<String>(); microList.add("123"); - List<Object> listId = new ArrayList<Object>(); + List<Object> listId = new ArrayList<Object>(); when(commonClassDao.getDataByColumn(Attribute.class, "xacmlId")).thenReturn(microList); List<Object> object = new ArrayList<>(); object.add(new Category()); @@ -83,9 +82,9 @@ public class DictionaryControllerTest { PolicyEditorScopes editorScope = new PolicyEditorScopes(); doNothing().when(commonClassDao).save(editorScope); doNothing().when(commonClassDao).update(editorScope); - + when(commonClassDao.getData(Attribute.class)).thenReturn(listId); - + request = mock(HttpServletRequest.class); controller = new DictionaryController(commonClassDao); new DictionaryUtils(commonClassDao); @@ -98,12 +97,13 @@ public class DictionaryControllerTest { public void testGetAttributeDictionaryEntityDatabyAttributeName() { logger.info("testGetAttributeDictionaryEntityDatabyAttributeName: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); controller.getAttributeDictionaryEntityDatabyAttributeName(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("attributeDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -116,12 +116,13 @@ public class DictionaryControllerTest { public void testGetAttributeDictionaryEntityData() { logger.info("testGetAttributeDictionaryEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); controller.getAttributeDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("attributeDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -134,16 +135,22 @@ public class DictionaryControllerTest { public void testSaveAttributeDictionary() { logger.info("testSaveAttributeDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); - + try { - jsonString = "{\"attributeDictionaryData\":{\"datatypeBean\":{\"shortName\":\"string\"},\"description\":\"Qwerty\",\"priority\":\"High\",\"userDataTypeValues\":[{\"$$hashKey\":\"object:641\",\"attributeValues\":\"test\",\"id\":\"choice1\"},{\"$$hashKey\":\"object:646\",\"attributeValues\":\"test\",\"id\":\"choice2\"}],\"xacmlId\":\"Qwerty\"},\"userid\":\"demo\"}"; + jsonString = + "{\"attributeDictionaryData\":{\"datatypeBean\":{\"shortName\":\"string\"},\"description\":" + + "\"Qwerty\",\"priority\":\"High\",\"userDataTypeValues\":[{\"$$hashKey\":" + + "\"object:641\",\"attributeValues\":\"test\",\"id\":\"choice1\"},{\"$$hashKey\":" + + "\"object:646\",\"attributeValues\":\"test\",\"id\":\"choice2\"}],\"xacmlId\":" + + "\"Qwerty\"},\"userid\":\"demo\"}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.saveAttributeDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("attributeDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -156,16 +163,17 @@ public class DictionaryControllerTest { public void testRemoveAttributeDictionary() { logger.info("testRemoveAttributeDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); try { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"xacmlId\":\"Test\"}}"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); + BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.removeAttributeDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("attributeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("attributeDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -178,12 +186,13 @@ public class DictionaryControllerTest { public void testGetOnapNameDictionaryByNameEntityData() { logger.info("testGetOnapNameDictionaryByNameEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); controller.getOnapNameDictionaryByNameEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("onapNameDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -196,12 +205,13 @@ public class DictionaryControllerTest { public void testGetOnapNameDictionaryEntityData() { logger.info("testGetOnapNameDictionaryEntityData: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); controller.getOnapNameDictionaryEntityData(response); try { - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("onapNameDictionaryDatas")); logger.info("response.getContentAsString(): " + response.getContentAsString()); } catch (UnsupportedEncodingException e) { fail("Exception: " + e); @@ -215,16 +225,18 @@ public class DictionaryControllerTest { logger.info("testSaveOnapDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); - + try { - jsonString = "{\"userid\":\"demo\",\"onapNameDictionaryData\":{\"description\":\"test\",\"onapName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"onapNameDictionaryData\":{\"description\":\"test\",\"onapName\":\"Test\"}}"; BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.saveOnapDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("onapNameDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); @@ -237,16 +249,17 @@ public class DictionaryControllerTest { public void testRemoveOnapDictionary() { logger.info("testRemoveOnapDictionary: Entering"); - MockHttpServletResponse response = new MockHttpServletResponse(); + MockHttpServletResponse response = new MockHttpServletResponse(); request = mock(HttpServletRequest.class); try { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"onapName\":\"Test\"}}"; - BufferedReader br = new BufferedReader(new StringReader(jsonString)); + BufferedReader br = new BufferedReader(new StringReader(jsonString)); when(request.getReader()).thenReturn(br); controller.removeOnapDictionary(request, response); logger.info("response.getContentAsString(): " + response.getContentAsString()); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("onapNameDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("onapNameDictionaryDatas")); } catch (Exception e) { fail("Exception: " + e); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java index 7ab1b170e..ef723a3fd 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/DictionaryImportControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -42,7 +43,7 @@ import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.dao.CommonClassDao; import org.springframework.mock.web.MockHttpServletResponse; -public class DictionaryImportControllerTest extends Mockito{ +public class DictionaryImportControllerTest extends Mockito { private static Logger logger = FlexLogger.getLogger(DictionaryImportController.class); @@ -59,20 +60,20 @@ public class DictionaryImportControllerTest extends Mockito{ controller = new DictionaryImportController(); new DictionaryImportController(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); } @Test - public void testIsValidDictionaryName(){ + public void testIsValidDictionaryName() { DictionaryImportController cotroller = new DictionaryImportController(); - //test invalid name + // test invalid name assertTrue(!cotroller.isValidDictionaryName("wrong-name")); - //test valid name + // test valid name assertTrue(cotroller.isValidDictionaryName("ActionList")); } @Test - public void testImportDictionaryData() throws ServletException, IOException{ + public void testImportDictionaryData() throws ServletException, IOException { List<String> fileNames = new ArrayList<>(); fileNames.add("Attribute.csv"); fileNames.add("ActionPolicyDictionary.csv"); @@ -99,9 +100,9 @@ public class DictionaryImportControllerTest extends Mockito{ fileNames.add("Settings.csv"); fileNames.add("Zone.csv"); fileNames.add("ActionList.csv"); - for(int i =0; i < fileNames.size(); i++){ - File file = new File("src/test/resources/dictionaryImport/"+fileNames.get(i)); - try(FileInputStream targetStream = new FileInputStream(file)){ + for (int i = 0; i < fileNames.size(); i++) { + File file = new File("src/test/resources/dictionaryImport/" + fileNames.get(i)); + try (FileInputStream targetStream = new FileInputStream(file)) { PushPolicyControllerTest pushController = new PushPolicyControllerTest(); when(request.getInputStream()).thenReturn(pushController.getInputStream(getBytes(targetStream))); when(request.getParameter("userId")).thenReturn("demo"); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java index 45d8466b6..b94e8d338 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/FirewallDictionaryControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -117,7 +118,8 @@ public class FirewallDictionaryControllerTest { @Test public void testGetProtocolListDictionaryEntityDataByName() { - test_WithGetDataByColumn(ProtocolList.class, "protocolListDictionaryDatas", "protocolName", + test_WithGetDataByColumn(ProtocolList.class, + "protocolListDictionaryDatas", "protocolName", () -> controller.getProtocolListDictionaryEntityDataByName(response)); } @@ -195,7 +197,8 @@ public class FirewallDictionaryControllerTest { @Test public void testGetZoneDictionaryEntityData() { - test_WithGetData(Zone.class, "zoneDictionaryDatas", () -> controller.getZoneDictionaryEntityData(response)); + test_WithGetData(Zone.class, "zoneDictionaryDatas", () -> + controller.getZoneDictionaryEntityData(response)); } @Test @@ -212,7 +215,8 @@ public class FirewallDictionaryControllerTest { @Test public void testGetFWDictListDictionaryEntityDataByName() { - test_WithGetDataByColumn(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName", + test_WithGetDataByColumn(FirewallDictionaryList.class, + "fwDictListDictionaryDatas", "parentItemName", () -> controller.getFWDictListDictionaryEntityDataByName(response)); } @@ -247,14 +251,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSavePrefixListDictionary() { - jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"description\":\"test\",\"prefixListName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"prefixListDictionaryData\":" + + "{\"description\":\"test\",\"prefixListName\":\"Test\"}}"; testSave(PrefixList.class, "prefixListDictionaryDatas", "prefixListName", () -> controller.savePrefixListDictionary(request, response)); } @Test public void testUpdatePrefixListDictionary() { - jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":" + + "\"test\",\"prefixListName\":\"Test\"}}"; testUpdate(PrefixList.class, "prefixListDictionaryDatas", "prefixListName", () -> controller.savePrefixListDictionary(request, response)); } @@ -268,20 +276,25 @@ public class FirewallDictionaryControllerTest { @Test public void testValidatePrefixListDictionary() { - jsonString = "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":\"test\",\"prefixListName\":\"Test\",\"prefixListValue\":\"10.10.10\"}}"; + jsonString = + "{\"userid\":\"demo\",\"prefixListDictionaryData\":{\"id\":1,\"description\":" + + "\"test\",\"prefixListName\":\"Test\",\"prefixListValue\":\"10.10.10\"}}"; testValidate(PrefixList.class, "result", () -> controller.validatePrefixListDictionary(request, response)); } @Test public void testSavePortListDictionary() { - jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"description\":\"test\",\"portName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"portListDictionaryData\":{\"description\":\"test\",\"portName\":\"Test\"}}"; testSave(PortList.class, "portListDictionaryDatas", "portName", () -> controller.savePortListDictionary(request, response)); } @Test public void testUpdatePortListDictionary() { - jsonString = "{\"userid\":\"demo\",\"portListDictionaryData\":{\"id\":1,\"description\":\"test\",\"portName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"portListDictionaryData\":{\"id\":1,\"description\":" + + "\"test\",\"portName\":\"Test\"}}"; testUpdate(PortList.class, "portListDictionaryDatas", "portName", () -> controller.savePortListDictionary(request, response)); } @@ -295,14 +308,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveProtocolListDictionary() { - jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"description\":\"test\",\"protocolName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"description\":\"test\",\"protocolName\":" + + "\"Test\"}}"; testSave(ProtocolList.class, "protocolListDictionaryDatas", "protocolName", () -> controller.saveProtocolListDictionary(request, response)); } @Test public void testUpdateProtocolListDictionary() { - jsonString = "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"id\":1,\"description\":\"test\",\"protocolName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"protocolListDictionaryData\":{\"id\":1,\"description\":" + + "\"test\",\"protocolName\":\"Test\"}}"; testUpdate(ProtocolList.class, "protocolListDictionaryDatas", "protocolName", () -> controller.saveProtocolListDictionary(request, response)); } @@ -316,14 +333,20 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveAddressGroupDictionary() { - jsonString = "{\"addressGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"addressGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":" + + "\"Test\"},\"userid\":\"demo\"}"; testSave(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test", () -> controller.saveAddressGroupDictionary(request, response)); } @Test public void testUpdateAddressGroupDictionary() { - jsonString = "{\"addressGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"addressGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:409\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"groupName\":\"Test\"},\"userid\":" + + "\"demo\"}"; testUpdate(AddressGroup.class, "addressGroupDictionaryDatas", "name", "Group_Test", () -> controller.saveAddressGroupDictionary(request, response)); } @@ -337,14 +360,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveActionListDictionary() { - jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"description\":\"test\",\"actionName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"description\":\"test\",\"actionName\":" + + "\"Test\"}}"; testSave(ActionList.class, "actionListDictionaryDatas", "actionName", () -> controller.saveActionListDictionary(request, response)); } @Test public void testUpdateActionListDictionary() { - jsonString = "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"id\":1,\"description\":\"test\",\"actionName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"actionListDictionaryData\":{\"id\":1,\"description\":\"test\",\"actionName\":" + + "\"Test\"}}"; testUpdate(ActionList.class, "actionListDictionaryDatas", "actionName", () -> controller.saveActionListDictionary(request, response)); } @@ -358,14 +385,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveServiceGroupDictionary() { - jsonString = "{\"serviceGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"serviceGroupDictionaryData\":{\"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}"; testSave(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test", () -> controller.saveServiceGroupDictionary(request, response)); } @Test public void testUpdateServiceGroupDictionary() { - jsonString = "{\"serviceGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"serviceGroupDictionaryData\":{\"id\":1, \"attributes\":[{\"$$hashKey\":\"object:657\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"groupName\":\"Test\"},\"userid\":\"demo\"}"; testUpdate(GroupServiceList.class, "serviceGroupDictionaryDatas", "name", "Group_Test", () -> controller.saveServiceGroupDictionary(request, response)); } @@ -379,14 +410,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveSecurityZoneDictionary() { - jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"description\":\"test\",\"zoneName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"description\":\"test\",\"zoneName\":" + + "\"Test\"}}"; testSave(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName", () -> controller.saveSecurityZoneDictionary(request, response)); } @Test public void testUpdateSecurityZoneDictionary() { - jsonString = "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"id\":1,\"description\":\"test\",\"zoneName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"securityZoneDictionaryData\":{\"id\":1,\"description\":\"test\",\"zoneName\":" + + "\"Test\"}}"; testUpdate(SecurityZone.class, "securityZoneDictionaryDatas", "zoneName", () -> controller.saveSecurityZoneDictionary(request, response)); } @@ -400,21 +435,33 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveServiceListDictionary() { - jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"serviceName\":" + + "\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; testSave(ServiceList.class, "serviceListDictionaryDatas", "serviceName", () -> controller.saveServiceListDictionary(request, response)); } @Test public void testUpdateServiceListDictionary() { - jsonString = "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"serviceListDictionaryData\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":" + + "\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; testUpdate(ServiceList.class, "serviceListDictionaryDatas", "serviceName", () -> controller.saveServiceListDictionary(request, response)); } @Test public void testRemoveServiceListDictionary() { - jsonString = "{\"data\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"data\":{\"appProtocols\":[{\"$$hashKey\":\"object:560\",\"id\":\"choice1\",\"option\":" + + "\"Test\"}],\"serviceDescription\":\"test\",\"id\":1,\"serviceName\":\"Test\",\"servicePorts\":" + + "\"1010\",\"transportProtocols\":[{\"$$hashKey\":\"object:555\",\"id\":\"choice1\",\"option\":" + + "\"Test\"}]},\"userid\":\"demo\"}"; testRemove(ServiceList.class, "serviceListDictionaryDatas", () -> controller.removeServiceListDictionary(request, response)); } @@ -422,12 +469,14 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveZoneDictionary() { jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}"; - testSave(Zone.class, "zoneDictionaryDatas", "zoneName", () -> controller.saveZoneDictionary(request, response)); + testSave(Zone.class, "zoneDictionaryDatas", "zoneName", () + -> controller.saveZoneDictionary(request, response)); } @Test public void testUpdateZoneDictionary() { - jsonString = "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}"; + jsonString = + "{\"userid\":\"demo\",\"zoneDictionaryData\":{\"id\":1,\"zoneValue\":\"test\",\"zoneName\":\"Test\"}}"; testUpdate(Zone.class, "zoneDictionaryDatas", "zoneName", () -> controller.saveZoneDictionary(request, response)); } @@ -440,14 +489,34 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveTermListDictionary() { - jsonString = "{\"termListDictionaryData\":{\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"termListDictionaryData\":{\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":" + + "\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":" + + "[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":" + + "[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":" + + "[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":" + + "\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":" + + "\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":" + + "\"Test\"}]},\"userid\":\"demo\"}"; testSave(TermList.class, "termListDictionaryDatas", "termName", () -> controller.saveTermListDictionary(request, response)); } @Test public void testUpdateTermListDictionary() { - jsonString = "{\"termListDictionaryData\":{\"id\":1,\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"termListDictionaryData\":{\"id\":1,\"actionListDatas\":[{\"$$hashKey\":\"object:1220\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"destinationListDatas\":[{\"$$hashKey\":" + + "\"object:1220\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"destinationServiceDatas\":" + + "[{\"$$hashKey\":\"object:1230\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"fromZoneDatas\":" + + "[{\"$$hashKey\":\"object:1245\",\"id\":\"choice1\",\"option\":\"Test\"}],\"sourceListDatas\":" + + "[{\"$$hashKey\":\"object:1215\",\"id\":\"choice1\",\"option\":" + + "\"Group_Test\"}],\"sourceServiceDatas\":[{\"$$hashKey\":\"object:1225\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"termDescription\":\"test\",\"termName\":" + + "\"Test\",\"toZoneDatas\":[{\"$$hashKey\":\"object:1240\",\"id\":\"choice1\",\"option\":" + + "\"Test\"}]},\"userid\":\"demo\"}"; testUpdate(TermList.class, "termListDictionaryDatas", "termName", () -> controller.saveTermListDictionary(request, response)); } @@ -461,14 +530,22 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveFWDictionaryList() { - jsonString = "{\"fwDictListDictionaryData\":{\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"fwDictListDictionaryData\":{\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":" + + "\"demo\"}"; testSave(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName", () -> controller.saveFWDictionaryList(request, response)); } @Test public void testUpdateFWDictionaryList() { - jsonString = "{\"fwDictListDictionaryData\":{\"id\":1,\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":\"demo\"}"; + jsonString = + "{\"fwDictListDictionaryData\":{\"id\":1,\"alAttributes\":[{\"$$hashKey\":\"object:1379\",\"id\":" + + "\"choice1\",\"option\":\"Group_Test\"}],\"attributes\":[{\"$$hashKey\":\"object:1374\",\"id\":" + + "\"choice1\",\"option\":\"Test\"}],\"description\":\"test\",\"parentItemName\":\"Test\"},\"userid\":" + + "\"demo\"}"; testUpdate(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName", () -> controller.saveFWDictionaryList(request, response)); } @@ -482,14 +559,20 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveFirewallTagPickerDictionary() { - jsonString = "{\"fwTagPickerDictionaryData\":{\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"fwTagPickerDictionaryData\":{\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":" + + "\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":" + + "\"Test\"}]},\"userid\":\"demo\"}"; testSave(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName", () -> controller.saveFirewallTagPickerDictionary(request, response)); } @Test public void testUpdateFirewallTagPickerDictionary() { - jsonString = "{\"fwTagPickerDictionaryData\":{\"id\":1,\"description\":\"test\",\"networkRole\":\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"fwTagPickerDictionaryData\":{\"id\":1,\"description\":\"test\",\"networkRole\":" + + "\"test\",\"tagPickerName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1855\",\"id\":" + + "\"choice1\",\"number\":\"test\",\"option\":\"Test\"}]},\"userid\":\"demo\"}"; testUpdate(FWTagPicker.class, "fwTagPickerDictionaryDatas", "tagPickerName", () -> controller.saveFirewallTagPickerDictionary(request, response)); } @@ -503,14 +586,18 @@ public class FirewallDictionaryControllerTest { @Test public void testSaveFirewallTagDictionary() { - jsonString = "{\"fwTagDictionaryData\":{\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"fwTagDictionaryData\":{\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":" + + "\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}"; testSave(FWTag.class, "fwTagDictionaryDatas", "fwTagName", () -> controller.saveFirewallTagDictionary(request, response)); } @Test public void testUpdateFirewallTagDictionary() { - jsonString = "{\"fwTagDictionaryData\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}"; + jsonString = + "{\"fwTagDictionaryData\":{\"id\":1,\"description\":\"test\",\"fwTagName\":\"Test\",\"tags\":" + + "[{\"$$hashKey\":\"object:1690\",\"id\":\"choice1\",\"tags\":\"test\"}]},\"userid\":\"demo\"}"; testUpdate(FWTag.class, "fwTagDictionaryDatas", "fwTagName", () -> controller.saveFirewallTagDictionary(request, response)); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java index e561a65b2..43cba2e61 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/MicroServiceDictionaryControllerTest.java @@ -20,7 +20,6 @@ * ============LICENSE_END========================================================= */ - package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -28,12 +27,15 @@ import static org.junit.Assert.fail; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.io.BufferedReader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; + import javax.servlet.http.HttpServletRequest; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -141,7 +143,6 @@ public class MicroServiceDictionaryControllerTest { logger.info("testSaveMicroServiceHeaderDefaultValues: exit"); } - @Test public void testGetMicroServiceHeaderDefaultsEntityDataByName() { logger.info("testGetMicroServiceHeaderDefaultsEntityDataByName: Entering"); @@ -215,7 +216,6 @@ public class MicroServiceDictionaryControllerTest { logger.info("testRemoveMicroServiceHeaderDefaults: exit"); } - @Test public void testGetDCAEUUIDDictionaryByNameEntityData() { diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java index 5e0b7ce28..451989c1f 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/OptimizationDictionaryControllerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -19,6 +19,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -26,12 +27,11 @@ import static org.junit.Assert.fail; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import java.io.BufferedReader; import java.io.StringReader; -import java.io.UnsupportedEncodingException; -import java.util.ArrayList; -import java.util.List; import javax.servlet.http.HttpServletRequest; + import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; @@ -39,14 +39,10 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.pap.xacml.rest.util.DictionaryUtils; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.DCAEuuid; -import org.onap.policy.rest.jpa.MicroServiceLocation; -import org.onap.policy.rest.jpa.MicroServiceModels; import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.UserInfo; import org.springframework.mock.web.MockHttpServletResponse; - public class OptimizationDictionaryControllerTest { private static Logger logger = FlexLogger.getLogger(OptimizationDictionaryControllerTest.class); @@ -63,8 +59,7 @@ public class OptimizationDictionaryControllerTest { UserInfo userInfo = new UserInfo(); userInfo.setUserLoginId("testUserId"); userInfo.setUserName("John"); - when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")) - .thenReturn(userInfo); + when(commonClassDao.getEntityItem(UserInfo.class, "userLoginId", "testing")).thenReturn(userInfo); OptimizationModels optimziationModels = new OptimizationModels(); @@ -76,19 +71,17 @@ public class OptimizationDictionaryControllerTest { HttpServletRequest request = Mockito.mock(HttpServletRequest.class); - jsonString = - "{\"optimizationModelsDictionaryData\": {\"modelName\": \"test\",\"inprocess\": false,\"model\":" - + " {\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," - + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", \"version\": \"\"," - + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," - + "\"recursive\": false}," - + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," - + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," - + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," - + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," - + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," - + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," - + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; + jsonString = "{\"optimizationModelsDictionaryData\": {\"modelName\": \"test\",\"inprocess\": false,\"model\":" + + " {\"name\": \"testingdata\",\"subScopename\": \"\",\"path\": [],\"type\": \"dir\"," + + "\"size\": 0,\"date\": \"2017-04-12T21:26:57.000Z\", \"version\": \"\"," + + "\"createdBy\": \"someone\",\"modifiedBy\": \"someone\",\"content\": \"\"," + "\"recursive\": false}," + + "\"tempModel\": {\"name\": \"testingdata\",\"subScopename\": \"\"}," + + "\"policy\": {\"policyType\": \"Config\",\"configPolicyType\": \"Micro Service\"," + + "\"policyName\": \"may1501\",\"policyDescription\": \"testing input\"," + + "\"onapName\": \"RaviTest\",\"guard\": \"False\",\"riskType\": \"Risk12345\"," + + "\"riskLevel\": \"2\",\"priority\": \"6\",\"serviceType\": \"DkatPolicyBody\"," + + "\"version\": \"1707.41.02\",\"ruleGridData\": [[\"fileId\"]],\"ttlDate\": null}}," + + "\"policyJSON\": {\"pmTableName\": \"test\",\"dmdTopic\": \"1\",\"fileId\": \"56\"}}"; br = new BufferedReader(new StringReader(jsonString)); // --- mock the getReader() call diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java index 9bf2ae590..f8273493b 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PolicyScopeDictionaryControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -55,7 +56,7 @@ public class PolicyScopeDictionaryControllerTest { private PolicyScopeDictionaryController controller = null; private MockHttpServletResponse response = null; private UserInfo userInfo; - private List<String> data; + private List<String> data; @Before public void setUp() throws Exception { @@ -76,7 +77,7 @@ public class PolicyScopeDictionaryControllerTest { controller.setCommonClassDao(commonClassDao); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); new DictionaryUtils(commonClassDao); DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); @@ -84,302 +85,339 @@ public class PolicyScopeDictionaryControllerTest { } @Test - public void testGetGroupPolicyScopeEntityDataByName(){ + public void testGetGroupPolicyScopeEntityDataByName() { when(commonClassDao.getDataByColumn(GroupPolicyScopeList.class, "name")).thenReturn(data); controller.getGroupPolicyScopeEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetGroupPolicyScopeEntityData(){ + public void testGetGroupPolicyScopeEntityData() { when(commonClassDao.getData(GroupPolicyScopeList.class)).thenReturn(new ArrayList<>()); controller.getGroupPolicyScopeEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSClosedLoopEntityDataByName(){ + public void testGetPSClosedLoopEntityDataByName() { when(commonClassDao.getDataByColumn(PolicyScopeClosedLoop.class, "name")).thenReturn(data); controller.getPSClosedLoopEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSClosedLoopEntityData(){ + public void testGetPSClosedLoopEntityData() { when(commonClassDao.getData(PolicyScopeClosedLoop.class)).thenReturn(new ArrayList<>()); controller.getPSClosedLoopEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSServiceEntityDataByName(){ + public void testGetPSServiceEntityDataByName() { when(commonClassDao.getDataByColumn(PolicyScopeService.class, "name")).thenReturn(data); controller.getPSServiceEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSServiceEntityData(){ + public void testGetPSServiceEntityData() { when(commonClassDao.getData(PolicyScopeService.class)).thenReturn(new ArrayList<>()); controller.getPSServiceEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSTypeEntityDataByName(){ + public void testGetPSTypeEntityDataByName() { when(commonClassDao.getDataByColumn(PolicyScopeType.class, "name")).thenReturn(data); controller.getPSTypeEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSTypeEntityData(){ + public void testGetPSTypeEntityData() { when(commonClassDao.getData(PolicyScopeType.class)).thenReturn(new ArrayList<>()); controller.getPSTypeEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSResourceEntityDataByName(){ + public void testGetPSResourceEntityDataByName() { when(commonClassDao.getDataByColumn(PolicyScopeResource.class, "name")).thenReturn(data); controller.getPSResourceEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetPSResourceEntityData(){ + public void testGetPSResourceEntityData() { when(commonClassDao.getData(PolicyScopeResource.class)).thenReturn(new ArrayList<>()); controller.getPSResourceEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSavePSGroupScopeDictionary(){ - jsonString = "{\"groupPolicyScopeListData\":{\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSavePSGroupScopeDictionary() { + jsonString = + "{\"groupPolicyScopeListData\":{\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSGroupScopeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSGroupScopeDictionary(){ - jsonString = "{\"groupPolicyScopeListData\":{\"id\":1,\"description\":\"test\",\"groupName\":\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePSGroupScopeDictionary() { + jsonString = + "{\"groupPolicyScopeListData\":{\"id\":1,\"description\":\"test\",\"groupName\":" + + "\"Test\"},\"groupPolicyScopeListData1\":{\"closedloop\":\"SampleClosedLoop\",\"resource\":" + + "\"SampleResource\",\"service\":\"SampleService\",\"type\":\"SampleType\"},\"userid\":\"demo\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSGroupScopeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSGroupScopeDictionary(){ + public void testRemovePSGroupScopeDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSGroupScopeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("groupPolicyScopeListDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("groupPolicyScopeListDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePSClosedLoopDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSavePSClosedLoopDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":" + + "\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSClosedLoopDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSClosedLoopDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePSClosedLoopDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psClosedLoopDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSClosedLoopDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSClosedLoopDictionary(){ + public void testRemovePSClosedLoopDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSClosedLoopDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psClosedLoopDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePSServiceDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSavePSServiceDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":" + + "\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSServiceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSServiceDictionary(){ + public void testUpdatePSServiceDictionary() { jsonString = "{\"userid\":\"demo\",\"psServiceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSServiceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSServiceDictionary(){ + public void testRemovePSServiceDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSServiceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psServiceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psServiceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePSTypeDictionary(){ + public void testSavePSTypeDictionary() { jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSTypeDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePSTypeDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSTypeDictionary(){ + public void testRemovePSTypeDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSavePSResourceDictionary(){ + public void testSavePSResourceDictionary() { jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSResourceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdatePSResourceDictionary(){ - jsonString = "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testUpdatePSResourceDictionary() { + jsonString = + "{\"userid\":\"demo\",\"psResourceDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":" + + "\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.savePSResourceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemovePSResourceDictionary(){ + public void testRemovePSResourceDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removePSResourceDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("psResourceDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("psResourceDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java index 007d02120..f9711b9ed 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/PushPolicyControllerTest.java @@ -22,7 +22,9 @@ package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.when; + import com.att.research.xacml.api.pap.PAPException; + import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; @@ -32,12 +34,14 @@ import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; + import javax.servlet.ReadListener; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.hibernate.SessionFactory; import org.junit.After; import org.junit.Before; @@ -52,7 +56,6 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyVersion; import org.springframework.mock.web.MockServletConfig; - public class PushPolicyControllerTest { private static Logger logger = FlexLogger.getLogger(PushPolicyControllerTest.class); @@ -68,7 +71,7 @@ public class PushPolicyControllerTest { @BeforeClass public static void beforeClassSetup() throws ServletException { - sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("pushcontrollertest"); + sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("pushcontrollertest"); } @Before @@ -82,7 +85,8 @@ public class PushPolicyControllerTest { servletConfig = Mockito.mock(MockServletConfig.class); System.setProperty("com.sun.management.jmxremote.port", "9993"); Mockito.when(servletConfig.getInitParameterNames()).thenReturn(Collections.enumeration(headers)); - Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")).thenReturn("src/test/resources/xacml.pap.properties"); + Mockito.when(servletConfig.getInitParameter("XACML_PROPERTIES_NAME")) + .thenReturn("src/test/resources/xacml.pap.properties"); commonClassDao = Mockito.mock(CommonClassDao.class); controller = new PushPolicyController(); @@ -91,35 +95,39 @@ public class PushPolicyControllerTest { } @Test - public void testPushPolicy() throws ServletException, PAPException{ + public void testPushPolicy() throws ServletException, PAPException { PolicyVersion versionData = new PolicyVersion(); - versionData.setPolicyName("com"+File.separator+"Config_Test"); + versionData.setPolicyName("com" + File.separator + "Config_Test"); versionData.setActiveVersion(1); versionData.setHigherVersion(1); List<Object> data = new ArrayList<>(); data.add(versionData); - when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(data); + when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com" + File.separator + "Config_Test")) + .thenReturn(data); pap = new XACMLPapServlet(); pap.init(servletConfig); callPushPolicy(); - when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com"+File.separator+"Config_Test")).thenReturn(null); + when(commonClassDao.getDataById(PolicyVersion.class, "policyName", "com" + File.separator + "Config_Test")) + .thenReturn(null); callPushPolicy(); } - public void callPushPolicy(){ - jsonString = "{\"policyScope\":\"com\",\"filePrefix\":\"Config_\",\"policyName\":\"Test\",\"pdpGroup\":\"default\"}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void callPushPolicy() { + jsonString = + "{\"policyScope\":\"com\",\"filePrefix\":\"Config_\",\"policyName\":\"Test\",\"pdpGroup\":\"default\"}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { char[] charBuffer = new char[8 * 1024]; StringBuilder builder = new StringBuilder(); int numCharsRead; while ((numCharsRead = br.read(charBuffer, 0, charBuffer.length)) != -1) { builder.append(charBuffer, 0, numCharsRead); } - when(request.getInputStream()).thenReturn(getInputStream(builder.toString().getBytes(StandardCharsets.UTF_8))); + when(request.getInputStream()) + .thenReturn(getInputStream(builder.toString().getBytes(StandardCharsets.UTF_8))); controller.pushPolicy(request, response); assertTrue(response != null); - }catch(Exception e){ - logger.error("Exception"+ e); + } catch (Exception e) { + logger.error("Exception" + e); } } @@ -148,9 +156,9 @@ public class PushPolicyControllerTest { return servletInputStream; } - @After - public void destroy(){ - if(pap!=null) - pap.destroy(); - } + @After + public void destroy() { + if (pap != null) + pap.destroy(); + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java index ae1840ebb..8292704b8 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/controller/SafePolicyControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.controller; import static org.junit.Assert.assertTrue; @@ -53,7 +54,7 @@ public class SafePolicyControllerTest { private SafePolicyController controller = null; private MockHttpServletResponse response = null; private UserInfo userInfo; - private List<String> data; + private List<String> data; @Before public void setUp() throws Exception { @@ -76,127 +77,139 @@ public class SafePolicyControllerTest { DictionaryUtils.setDictionaryUtils(new DictionaryUtils()); mock(DictionaryUtils.class); request = Mockito.mock(HttpServletRequest.class); - response = new MockHttpServletResponse(); + response = new MockHttpServletResponse(); logger.info("setUp: exit"); } @Test - public void testGetRiskTypeDictionaryByNameEntityData(){ + public void testGetRiskTypeDictionaryByNameEntityData() { when(commonClassDao.getDataByColumn(RiskType.class, "name")).thenReturn(data); controller.getRiskTypeDictionaryByNameEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetRiskTypeDictionaryEntityData(){ + public void testGetRiskTypeDictionaryEntityData() { when(commonClassDao.getData(RiskType.class)).thenReturn(new ArrayList<>()); controller.getRiskTypeDictionaryEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetSafePolicyWarningEntityDataByName(){ + public void testGetSafePolicyWarningEntityDataByName() { when(commonClassDao.getDataByColumn(SafePolicyWarning.class, "name")).thenReturn(data); controller.getSafePolicyWarningEntityDataByName(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testGetSafePolicyWarningeEntityData(){ + public void testGetSafePolicyWarningeEntityData() { when(commonClassDao.getData(SafePolicyWarning.class)).thenReturn(new ArrayList<>()); controller.getSafePolicyWarningeEntityData(response); try { - assertTrue(response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); } catch (Exception e) { fail(); - logger.error(e.getMessage(),e); + logger.error(e.getMessage(), e); } } @Test - public void testSaveRiskTypeDictionary(){ - jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveRiskTypeDictionary() { + jsonString = + "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveRiskTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateRiskTypeDictionary(){ + public void testUpdateRiskTypeDictionary() { jsonString = "{\"userid\":\"demo\",\"riskTypeDictionaryData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveRiskTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveRiskTypeDictionary(){ + public void testRemoveRiskTypeDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeRiskTypeDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("riskTypeDictionaryDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("riskTypeDictionaryDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testSaveSafePolicyWarningDictionary(){ - jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + public void testSaveSafePolicyWarningDictionary() { + jsonString = + "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveSafePolicyWarningDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testUpdateSafePolicyWarningDictionary(){ + public void testUpdateSafePolicyWarningDictionary() { jsonString = "{\"userid\":\"demo\",\"safePolicyWarningData\":{\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.saveSafePolicyWarningDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } @Test - public void testRemoveSafePolicyWarningDictionary(){ + public void testRemoveSafePolicyWarningDictionary() { jsonString = "{\"userid\":\"demo\",\"data\":{\"id\":1,\"description\":\"test\",\"name\":\"Test\"}}"; - try(BufferedReader br = new BufferedReader(new StringReader(jsonString))){ + try (BufferedReader br = new BufferedReader(new StringReader(jsonString))) { when(request.getReader()).thenReturn(br); controller.removeSafePolicyWarningDictionary(request, response); - assertTrue( response.getContentAsString() != null && response.getContentAsString().contains("safePolicyWarningDatas")); - }catch(Exception e){ - logger.error("Exception"+ e); + assertTrue(response.getContentAsString() != null + && response.getContentAsString().contains("safePolicyWarningDatas")); + } catch (Exception e) { + logger.error("Exception" + e); } } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java index da9c4e8f5..2b95be068 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElasticSearchPolicyUpdateTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk; import static org.junit.Assert.assertTrue; @@ -46,21 +47,21 @@ public class ElasticSearchPolicyUpdateTest { private XACMLPAPTest papTest; @Before - public void setUp() throws IOException, ServletException, SQLException{ + public void setUp() throws IOException, ServletException, SQLException { // Set the system property temporarily System.setProperty("PROPERTY_FILE", "src/test/resources/policyelk.properties"); try { ClassLoader classLoader = getClass().getClassLoader(); policyContent = IOUtils.toString(classLoader.getResourceAsStream("Config_SampleTest1206.1.xml")); } catch (Exception e1) { - logger.error("Exception Occured"+e1); + logger.error("Exception Occured" + e1); } papTest = new XACMLPAPTest(); papTest.setDBDao(); } @Test - public void testElasticSearchMainFunction() throws SQLException{ + public void testElasticSearchMainFunction() throws SQLException { ConfigurationDataEntity configurationEntity = new ConfigurationDataEntity(); configurationEntity.setConfigBody("Sample Test"); configurationEntity.setConfigType("OTHER"); @@ -68,8 +69,7 @@ public class ElasticSearchPolicyUpdateTest { configurationEntity.setDescription("test"); configurationEntity.setModifiedBy("Test"); configurationEntity.setModifiedDate(new Date()); - - + PolicyEntity entity = new PolicyEntity(); entity.setPolicyName("Config_SampleTest.1.xml"); entity.setPolicyData(policyContent.toString()); @@ -91,7 +91,7 @@ public class ElasticSearchPolicyUpdateTest { } @After - public void reset(){ + public void reset() { System.clearProperty("PROPERTY_FILE"); } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java index 2f3d580f7..87f56e284 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/ElkConnectorImplTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017-2019 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. @@ -25,6 +25,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; + import io.searchbox.client.JestResult; import java.io.IOException; @@ -56,41 +57,41 @@ public class ElkConnectorImplTest { } @Test - public void searchTest(){ - JestResult r1=null, r2=null, r3=null, r4=null; + public void searchTest() { + JestResult r1 = null, r2 = null, r3 = null, r4 = null; // Should always work if the above test passes and ELK server is up - try{ + try { r1 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123"); } catch (Exception e) { // ELK server is down. Don't continue the test - if(e instanceof IllegalStateException){ + if (e instanceof IllegalStateException) { return; } fail(); } // Should always work - try{ + try { r2 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The_quick_brown_fox_jumps_over_the_lazy_dog"); } catch (Exception e) { fail(); } // Should throw exception - try{ + try { r3 = new ElkConnectorImpl().search(PolicyIndexType.decision, "abc123{}"); } catch (Exception e) { - if(! (e instanceof IllegalArgumentException)){ + if (!(e instanceof IllegalArgumentException)) { fail(); } } // Should throw exception - try{ + try { r4 = new ElkConnectorImpl().search(PolicyIndexType.decision, "The quick brown fox jumps over the lazy dog"); } catch (Exception e) { - if(! (e instanceof IllegalArgumentException)){ + if (!(e instanceof IllegalArgumentException)) { fail(); } } @@ -114,7 +115,6 @@ public class ElkConnectorImplTest { fail("Expected exception to be thrown"); } - @Test public void testPut() throws IOException { thrown.expect(NullPointerException.class); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java index 0b8c86c1e..7d6b90831 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PairTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.elk; import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.onap.policy.pap.xacml.rest.elk.client.Pair; diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java index 76c0ce788..401e419bb 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticDataTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -21,9 +21,11 @@ package org.onap.policy.pap.xacml.rest.elk; import static org.junit.Assert.assertEquals; + import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; + import org.junit.Test; import org.onap.policy.pap.xacml.rest.elk.client.PolicyElasticData; import org.onap.policy.rest.adapter.PolicyRestAdapter; @@ -103,7 +105,7 @@ public class PolicyElasticDataTest { data.setSupressionType(testVal); assertEquals(data.getSupressionType(), testVal); data.setServiceType(testVal); - assertEquals(data.getServiceType(),testVal); + assertEquals(data.getServiceType(), testVal); data.setUuid(testVal); assertEquals(data.getUuid(), testVal); data.setLocation(testVal); @@ -111,7 +113,7 @@ public class PolicyElasticDataTest { data.setPriority(testVal); assertEquals(data.getPriority(), testVal); data.setMsLocation(testVal); - assertEquals(data.getMsLocation(),testVal); + assertEquals(data.getMsLocation(), testVal); data.setRuleName(testVal); assertEquals(data.getRuleName(), testVal); data.setBrmsParamBody(testMap); diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java index bdbe1441d..9456dd4e4 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyElasticSearchControllerTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,6 +17,7 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.rest.elk; import static org.junit.Assert.assertEquals; @@ -42,14 +43,14 @@ public class PolicyElasticSearchControllerTest { private HttpServletResponse response = null; @Before - public void setup(){ + public void setup() { conroller = new PolicyElasticSearchController(); request = Mockito.mock(HttpServletRequest.class); response = Mockito.mock(HttpServletResponse.class); } @Test - public void testSearchDictionary(){ + public void testSearchDictionary() { List<String> jsonString = new ArrayList<>(); jsonString.add("{\"type\":\"attribute\",\"data\":{\"xacmlId\":\"Test\"}}"); jsonString.add("{\"type\":\"onapName\",\"data\":{\"onapName\":\"Test\"}}"); @@ -69,8 +70,8 @@ public class PolicyElasticSearchControllerTest { jsonString.add("{\"type\":\"psGroupPolicy\",\"data\":{\"name\":\"Test\"}}"); jsonString.add("{\"type\":\"safeRisk\",\"data\":{\"name\":\"Test\"}}"); jsonString.add("{\"type\":\"safePolicyWarning\",\"data\":{\"name\":\"Test\"}}"); - for(int i = 0; i < jsonString.size(); i++){ - try(BufferedReader br = new BufferedReader(new StringReader(jsonString.get(i)))) { + for (int i = 0; i < jsonString.size(); i++) { + try (BufferedReader br = new BufferedReader(new StringReader(jsonString.get(i)))) { when(request.getReader()).thenReturn(br); conroller.searchDictionary(request, response); } catch (Exception e) { diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java index 7df295382..bffdf3d79 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/elk/PolicyLocatorTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -21,6 +21,7 @@ package org.onap.policy.pap.xacml.rest.elk; import static org.junit.Assert.assertEquals; + import org.junit.Test; import org.onap.policy.pap.xacml.rest.elk.client.PolicyLocator; @@ -35,8 +36,7 @@ public class PolicyLocatorTest { String version = "1.0"; String testString = "[owner|scope|type|name|id|v1.0|]"; - PolicyLocator locator = new PolicyLocator(policyType, policyName, owner, - scope, policyId, version); + PolicyLocator locator = new PolicyLocator(policyType, policyName, owner, scope, policyId, version); String locatorString = locator.toString(); assertEquals(locatorString, testString); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java index 008f2629e..17967a4bb 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DeleteHandlerTest.java @@ -26,10 +26,13 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; + import com.mockrunner.mock.web.MockHttpServletRequest; import com.mockrunner.mock.web.MockHttpServletResponse; + import java.util.Collections; import java.util.List; + import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; @@ -93,31 +96,30 @@ public class DeleteHandlerTest { PolicyElasticSearchController controller = Mockito.mock(PolicyElasticSearchController.class); PowerMockito.whenNew(PolicyElasticSearchController.class).withNoArguments().thenReturn(controller); - // Test deletion from PAP - MockHttpServletResponse response = new MockHttpServletResponse(); - try { - handler.doApiDeleteFromPap(request, response); - } catch (Exception ex) { - fail("Not expecting an exception: " + ex); - } + // Test deletion from PAP + MockHttpServletResponse response = new MockHttpServletResponse(); + try { + handler.doApiDeleteFromPap(request, response); + } catch (Exception ex) { + fail("Not expecting an exception: " + ex); + } // Test deletion from PDP OnapLoggingContext loggingContext = Mockito.mock(OnapLoggingContext.class); try { handler.doApiDeleteFromPdp(request, response, loggingContext); - } - catch (Exception ex) { + } catch (Exception ex) { fail("Not expecting an exception: " + ex); } - // Test delete entity - PolicyEntity policyEntity = new PolicyEntity(); - policyEntity.setPolicyName("testVal"); - String result = DeleteHandler.deletePolicyEntityData(policyEntity); - assertEquals(result, "success"); + // Test delete entity + PolicyEntity policyEntity = new PolicyEntity(); + policyEntity.setPolicyName("testVal"); + String result = DeleteHandler.deletePolicyEntityData(policyEntity); + assertEquals(result, "success"); - // Test check entity - List<?> peResult = Collections.emptyList(); - assertEquals(DeleteHandler.checkPolicyGroupEntity(peResult), false); - } + // Test check entity + List<?> peResult = Collections.emptyList(); + assertEquals(DeleteHandler.checkPolicyGroupEntity(peResult), false); + } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java index ca6860ae8..8c35c17ef 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/DictionaryHandlerTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.handler; import static org.junit.Assert.assertNull; + import org.junit.Test; public class DictionaryHandlerTest { diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java index 3daed2455..ae6235f0e 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/handler/PushPolicyHandlerTest.java @@ -25,13 +25,17 @@ import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; + import com.mockrunner.mock.web.MockHttpServletResponse; + import java.io.File; import java.util.ArrayList; import java.util.List; + import javax.script.SimpleBindings; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.junit.Test; import org.mockito.Mockito; import org.onap.policy.rest.dao.CommonClassDao; @@ -40,7 +44,6 @@ import org.onap.policy.xacml.api.pap.OnapPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPPolicy; - public class PushPolicyHandlerTest { @Test public void testGetsAndChecks() { diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java index e7de8d0c4..550b1527c 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/jpa/PolicyEntityTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017, 2019 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. @@ -22,14 +22,9 @@ package org.onap.policy.pap.xacml.rest.jpa; import static org.junit.Assert.*; -//import org.apache.commons.logging.Log; -//import org.apache.commons.logging.LogFactory; -import org.junit.*; -import org.onap.policy.rest.XACMLRestProperties; -import org.onap.policy.rest.jpa.ActionBodyEntity; -import org.onap.policy.rest.jpa.ConfigurationDataEntity; -import org.onap.policy.rest.jpa.PolicyDBDaoEntity; -import org.onap.policy.rest.jpa.PolicyEntity; +import java.util.Date; +import java.util.List; +import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; @@ -37,21 +32,23 @@ import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import javax.persistence.Query; -import java.util.Date; -import java.util.List; -import org.onap.policy.common.logging.flexlogger.FlexLogger; +import org.junit.*; +import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; - -import java.util.Properties; +import org.onap.policy.rest.XACMLRestProperties; +import org.onap.policy.rest.jpa.ActionBodyEntity; +import org.onap.policy.rest.jpa.ConfigurationDataEntity; +import org.onap.policy.rest.jpa.PolicyDBDaoEntity; +import org.onap.policy.rest.jpa.PolicyEntity; public class PolicyEntityTest { private static Logger logger = FlexLogger.getLogger(PolicyEntityTest.class); @Test - public void testAllOps(){ + public void testAllOps() { Properties properties = new Properties(); - properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER,"org.h2.Driver"); + properties.put(XACMLRestProperties.PROP_PAP_DB_DRIVER, "org.h2.Driver"); properties.put(XACMLRestProperties.PROP_PAP_DB_URL, "jdbc:h2:file:./sql/xacmlTest"); properties.put(XACMLRestProperties.PROP_PAP_DB_USER, "sa"); properties.put(XACMLRestProperties.PROP_PAP_DB_PASSWORD, ""); @@ -61,536 +58,500 @@ public class PolicyEntityTest { EntityTransaction et = em.getTransaction(); et.begin(); - //Make sure the DB is clean + // Make sure the DB is clean em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - //Create a policy object + // Create a policy object PolicyEntity p1 = new PolicyEntity(); - - //persist the policy + + // persist the policy em.persist(p1); long policyId1 = p1.getPolicyId(); - + String policyName1 = p1.getPolicyName(); - + int version1 = p1.getVersion(); - + String policyData1 = p1.getPolicyData(); - + ConfigurationDataEntity configData1 = p1.getConfigurationData(); - String configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null"); - + String configDataStr1 = (configData1 != null ? "configurationDataId = " + configData1.getConfigurationDataId() + : "configurationData is null"); + ActionBodyEntity actionBody1 = p1.getActionBodyEntity(); - String actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); - + String actionBodyStr1 = + (actionBody1 != null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); + String createdBy1 = p1.getCreatedBy(); - + Date createdDate1 = p1.getCreatedDate(); String createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null"); - + String description = p1.getDescription(); - + String modifiedBy1 = p1.getModifiedBy(); - + Date modifiedDate1 = p1.getModifiedDate(); String modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null"); - - - logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects before persist*********" - + "\npolicyId1 = " + policyId1 - + "\npolicyName1 = " + policyName1 - + "\nversion1 = " + version1 - + "\npolicyData1 = " + policyData1 - + "\nconfigDataStr1 = " + configDataStr1 - + "\nactionBodyStr1 = " + actionBodyStr1 - + "\nscope = " + p1.getScope() - + "\ncreatedBy1 = " + createdBy1 - + "\ncreatedDateStr1 = " + createdDateStr1 - + "\ndescription = " + description - + "\nmodifiedBy1 = " + modifiedBy1 - + "\nmodifiedDateStr1 = " + modifiedDateStr1 - + "\ndeleted = " + p1.isDeleted()); - - //Set policyID + + logger.debug( + "\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects before persist*********" + + "\npolicyId1 = " + policyId1 + "\npolicyName1 = " + policyName1 + "\nversion1 = " + version1 + + "\npolicyData1 = " + policyData1 + "\nconfigDataStr1 = " + configDataStr1 + + "\nactionBodyStr1 = " + actionBodyStr1 + "\nscope = " + p1.getScope() + "\ncreatedBy1 = " + + createdBy1 + "\ncreatedDateStr1 = " + createdDateStr1 + "\ndescription = " + description + + "\nmodifiedBy1 = " + modifiedBy1 + "\nmodifiedDateStr1 = " + modifiedDateStr1 + "\ndeleted = " + + p1.isDeleted()); + + // Set policyID p1.setPolicyName("testPID2"); - - //Set policyData + + // Set policyData p1.setPolicyData("<policy>PolicyData</policy>"); - - //We will NOT set the ConfigurationDataEntity or ActionBodyEntity object just to test that it is optional - - //set createdBy + + // We will NOT set the ConfigurationDataEntity or ActionBodyEntity object just to test that it is optional + + // set createdBy p1.setCreatedBy("kevin"); - - //createdDate will be set when it is persisted - - //set scope + + // createdDate will be set when it is persisted + + // set scope p1.setScope("mckiou.kevin"); - - //set description + + // set description p1.setDescription("PolicyEntity Description"); - - //set modifiedBy + + // set modifiedBy p1.setModifiedBy("kevin"); - - //modifiedDate will be set when it is persisted - - //Flush to the DB + + // modifiedDate will be set when it is persisted + + // Flush to the DB em.flush(); - - //Now lets get some attribute values - + + // Now lets get some attribute values + policyId1 = p1.getPolicyId(); - + policyName1 = p1.getPolicyName(); - + version1 = p1.getVersion(); - + policyData1 = p1.getPolicyData(); - + configData1 = p1.getConfigurationData(); - configDataStr1 = (configData1!=null ? "configurationDataId = " + configData1.getConfigurationDataId() : "configurationData is null"); - + configDataStr1 = (configData1 != null ? "configurationDataId = " + configData1.getConfigurationDataId() + : "configurationData is null"); + actionBody1 = p1.getActionBodyEntity(); - actionBodyStr1 = (actionBody1!=null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); - + actionBodyStr1 = + (actionBody1 != null ? "actionBodyId = " + actionBody1.getActionBodyId() : "actionBody is null"); + createdBy1 = p1.getCreatedBy(); - + createdDate1 = p1.getCreatedDate(); createdDateStr1 = (createdDate1 != null ? createdDate1.toString() : "createdDate is null"); - + description = p1.getDescription(); - + modifiedBy1 = p1.getModifiedBy(); - + modifiedDate1 = p1.getModifiedDate(); modifiedDateStr1 = (modifiedDate1 != null ? modifiedDate1.toString() : "modifiedDate is null"); - - logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects after persist*********" - + "\npolicyId1 = " + policyId1 - + "\npolicyName1 = " + policyName1 - + "\nversion1 = " + version1 - + "\npolicyData1 = " + policyData1 - + "\nconfigDataStr1 = " + configDataStr1 - + "\nactionBodyStr1 = " + actionBodyStr1 - + "\nscopeId = " + p1.getScope() - + "\ncreatedBy1 = " + createdBy1 - + "\ncreatedDateStr1 = " + createdDateStr1 - + "\ndescription = " + description - + "\nmodifiedBy1 = " + modifiedBy1 - + "\nmodifiedDateStr1 = " + modifiedDateStr1 - + "\ndeleted = " + p1.isDeleted()); - - //Now lets fully configure the configurationData and actionBody - - //Create a ConfigurationDataEntity object and set ID - ConfigurationDataEntity c1 = new ConfigurationDataEntity(); - - ActionBodyEntity a1 = new ActionBodyEntity(); - - //persist the configuration Data + + logger.debug("\n\n********PolicyEntityTest: Local PolicyEntity and Configuration objects after " + + "persist*********" + + "\npolicyId1 = " + policyId1 + "\npolicyName1 = " + policyName1 + "\nversion1 = " + version1 + + "\npolicyData1 = " + policyData1 + "\nconfigDataStr1 = " + configDataStr1 + "\nactionBodyStr1 = " + + actionBodyStr1 + "\nscopeId = " + p1.getScope() + "\ncreatedBy1 = " + createdBy1 + + "\ncreatedDateStr1 = " + createdDateStr1 + "\ndescription = " + description + "\nmodifiedBy1 = " + + modifiedBy1 + "\nmodifiedDateStr1 = " + modifiedDateStr1 + "\ndeleted = " + p1.isDeleted()); + + // Now lets fully configure the configurationData and actionBody + + // Create a ConfigurationDataEntity object and set ID + ConfigurationDataEntity c1 = new ConfigurationDataEntity(); + + ActionBodyEntity a1 = new ActionBodyEntity(); + + // persist the configuration Data em.persist(c1); - + c1.setConfigType("OTHER"); - + c1.setConfigBody("ABC"); - + c1.setDescription("ConfigurationDataEntity Description"); - + c1.setCreatedBy("kevin"); - - //c1.setModifiedBy("kevin"); - + + // c1.setModifiedBy("kevin"); + c1.setDeleted(true); - - //persist the action Body - + + // persist the action Body + em.persist(a1); - + a1.setActionBody("myActionBody"); - + a1.setActionBodyName("myActionBodyName"); - + a1.setCreatedBy("kevin"); - + a1.setModifiedBy("kevin"); - + a1.setDeleted(false); - - + long configurationDataId = c1.getConfigurationDataId(); - + int cdVersion = c1.getVersion(); - + String cdConfigType = c1.getConfigType(); - + String cdConfigBody = c1.getConfigBody(); - + String cdCreatedBy = c1.getCreatedBy(); - + Date cdCreatedDate = c1.getCreatedDate(); - + String cdDescription = c1.getDescription(); - + String cdModifiedBy = c1.getModifiedBy(); - + Date cdModifiedDate = c1.getModifiedDate(); - + logger.debug("\n\n********PolicyEntityTest: Local Configuration object after setting values *********" - + "\nconfigurationDataId = " + configurationDataId - + "\ncdVersion = " + cdVersion - + "\ncdConfigType = " + cdConfigType - + "\ncdConfigBody = " + cdConfigBody - + "\ncdCreatedBy = " + cdCreatedBy - + "\ncdCreatedDate = " + cdCreatedDate - + "\ncdDescription = " + cdDescription - + "\ncdModifiedBy = " + cdModifiedBy - + "\ncdModifiedDate = " + cdModifiedDate - + "\ndeleted = " + c1.isDeleted()); - - - + + "\nconfigurationDataId = " + configurationDataId + "\ncdVersion = " + cdVersion + "\ncdConfigType = " + + cdConfigType + "\ncdConfigBody = " + cdConfigBody + "\ncdCreatedBy = " + cdCreatedBy + + "\ncdCreatedDate = " + cdCreatedDate + "\ncdDescription = " + cdDescription + "\ncdModifiedBy = " + + cdModifiedBy + "\ncdModifiedDate = " + cdModifiedDate + "\ndeleted = " + c1.isDeleted()); + logger.debug("\n\n********PolicyEntityTest: Local Action Body object after setting values *********" - + "\nactionBodyId = " + a1.getActionBodyId() - + "\nactionBodyVersion = " + a1.getVersion() - + "\nactionBody = " + a1.getActionBody() - + "\nactionBodyCeatedBy = " + a1.getCreatedBy() - + "\nactionBodyCreatedDate = " + a1.getCreatedDate() - + "\nactionBodyModifiedBy = " + a1.getModifiedBy() - + "\nactionBodyModifiedDate = " + a1.getModifiedDate() - + "\nactionBodyDeleted = " + a1.isDeleted()); - - p1.setScope("mckiou.kevin.kim"); - - //flush to the db + + "\nactionBodyId = " + a1.getActionBodyId() + "\nactionBodyVersion = " + a1.getVersion() + + "\nactionBody = " + a1.getActionBody() + "\nactionBodyCeatedBy = " + a1.getCreatedBy() + + "\nactionBodyCreatedDate = " + a1.getCreatedDate() + "\nactionBodyModifiedBy = " + a1.getModifiedBy() + + "\nactionBodyModifiedDate = " + a1.getModifiedDate() + "\nactionBodyDeleted = " + a1.isDeleted()); + + p1.setScope("mckiou.kevin.kim"); + + // flush to the db em.flush(); - - //Perform policy selects - + + // Perform policy selects + Query query = em.createQuery("Select p from PolicyEntity p where p.policyId=:pid"); Query queryscope = em.createQuery("Select p from PolicyEntity p where p.scope=:s"); - + query.setParameter("pid", p1.getPolicyId()); queryscope.setParameter("s", "mckiou.kevin.kim"); - - //Just test that we are retrieving the right object + + // Just test that we are retrieving the right object @SuppressWarnings("rawtypes") List psList = queryscope.getResultList(); PolicyEntity px = null; - if(!psList.isEmpty()){ - //ignores multiple results + if (!psList.isEmpty()) { + // ignores multiple results px = (PolicyEntity) psList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No PolicyEntity using scope DB entry found"); } - - //The scope object on the retrieved policy object should be same as the one we used to find it - assertSame(p1,px); - - - //Because getSingleResult() throws an unchecked exception which is an indication of a - //programming error, we are not going to use it. + + // The scope object on the retrieved policy object should be same as the one we used to find it + assertSame(p1, px); + + // Because getSingleResult() throws an unchecked exception which is an indication of a + // programming error, we are not going to use it. @SuppressWarnings("rawtypes") List resultList = query.getResultList(); PolicyEntity p2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results p2 = (PolicyEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No PolicyEntity DB entry found"); } - - logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB BEFORE assigning configurationData*********" - + "\npolicyId2 = " + p2.getPolicyId() - + "\npolicyName2 = " + p2.getPolicyName() - + "\nversion2 = " + p2.getVersion() - + "\npolicyData2 = " + p2.getPolicyData() - + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") - + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") - + "\nscope2 = " + p2.getScope() - + "\ncreatedBy2 = " + p2.getCreatedBy() - + "\ncreatedDate2 = " + p2.getCreatedDate() - + "\ndescription2 = " + p2.getDescription() - + "\nmodifiedBy2 = " + p2.getModifiedBy() - + "\nmodifiedDate2 = " + p2.getModifiedDate() - + "\ndeleted2 = " + p2.isDeleted()); - - //Confirm that the retrieved policy object is the same as the persisted object - assertSame(p1,p2); - - //Perform configurationData selects + + logger.debug( + "\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB BEFORE assigning " + + "configurationData*********" + + "\npolicyId2 = " + p2.getPolicyId() + "\npolicyName2 = " + p2.getPolicyName() + + "\nversion2 = " + p2.getVersion() + "\npolicyData2 = " + p2.getPolicyData() + + "\nconfigurationData2 = " + + (p2.getConfigurationData() != null + ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() + : "configurationData is null") + + "\nactionBody2 = " + + (p2.getActionBodyEntity() != null + ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() + : "actionBody is null") + + "\nscope2 = " + p2.getScope() + "\ncreatedBy2 = " + p2.getCreatedBy() + "\ncreatedDate2 = " + + p2.getCreatedDate() + "\ndescription2 = " + p2.getDescription() + "\nmodifiedBy2 = " + + p2.getModifiedBy() + "\nmodifiedDate2 = " + p2.getModifiedDate() + "\ndeleted2 = " + + p2.isDeleted()); + + // Confirm that the retrieved policy object is the same as the persisted object + assertSame(p1, p2); + + // Perform configurationData selects Query query2 = em.createQuery("Select c from ConfigurationDataEntity c where c.configurationDataId=:cid"); - + query2.setParameter("cid", c1.getConfigurationDataId()); - - //Get the database version of the Configuration Data + + // Get the database version of the Configuration Data resultList = query2.getResultList(); ConfigurationDataEntity c2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results c2 = (ConfigurationDataEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found"); } - - logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB BEFORE assigning to policy*********" - + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() - + "\nversion2 = " + c2.getVersion() - + "\nconfigType2 = " + c2.getConfigType() - + "\nconfigBody2 = " + c2.getConfigBody() - + "\ncreatedBy2 = " + c2.getCreatedBy() - + "\ncreatedDate2 = " + c2.getCreatedDate() - + "\ndescription2 = " + c2.getDescription() - + "\nmodifiedBy2 = " + c2.getModifiedBy() - + "\nmodifiedDate2 = " + c2.getModifiedDate() - + "\ndeleted2 = " + c2.isDeleted()); - - //Confirm the retrieved ConfigurationDataEntity object is the same as the persisted - assertSame(c1,c2); - - //Now assign the configurationData to the policy + + logger.debug( + "\n\n********PolicyEntityTest: Configuration object after retrieving from DB BEFORE assigning to " + + "policy*********" + + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() + "\nversion2 = " + c2.getVersion() + + "\nconfigType2 = " + c2.getConfigType() + "\nconfigBody2 = " + c2.getConfigBody() + + "\ncreatedBy2 = " + c2.getCreatedBy() + "\ncreatedDate2 = " + c2.getCreatedDate() + + "\ndescription2 = " + c2.getDescription() + "\nmodifiedBy2 = " + c2.getModifiedBy() + + "\nmodifiedDate2 = " + c2.getModifiedDate() + "\ndeleted2 = " + c2.isDeleted()); + + // Confirm the retrieved ConfigurationDataEntity object is the same as the persisted + assertSame(c1, c2); + + // Now assign the configurationData to the policy p1.setConfigurationData(c1); - - //Perform actionBody selects + + // Perform actionBody selects Query querya2 = em.createQuery("Select a from ActionBodyEntity a where a.actionBodyId=:aid"); - + querya2.setParameter("aid", a1.getActionBodyId()); - - //Get the database version of the Action Body + + // Get the database version of the Action Body resultList = querya2.getResultList(); ActionBodyEntity a2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results a2 = (ActionBodyEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found"); } - - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB BEFORE assigning to policy *********" - + "\nactionBodyId2 = " + a2.getActionBodyId() - + "\nactionBodyVersion2 = " + a2.getVersion() - + "\nactionBody2 = " + a2.getActionBody() - + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() - + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() - + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() - + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() - + "\nactionBodyDeleted2 = " + a2.isDeleted()); - - - //Confirm the retrieved ActionBodyEntity object is the same as the persisted - assertSame(a1,a2); - - //Now assign the ActionBodyEntity to the policy + + logger.debug( + "\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB BEFORE assigning to " + + "policy *********" + + "\nactionBodyId2 = " + a2.getActionBodyId() + "\nactionBodyVersion2 = " + a2.getVersion() + + "\nactionBody2 = " + a2.getActionBody() + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() + + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() + "\nactionBodyModifiedBy2 = " + + a2.getModifiedBy() + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() + + "\nactionBodyDeleted2 = " + a2.isDeleted()); + + // Confirm the retrieved ActionBodyEntity object is the same as the persisted + assertSame(a1, a2); + + // Now assign the ActionBodyEntity to the policy p1.setActionBodyEntity(a1); em.flush(); - - //Let's retrieve the policy, configurationData and actionBody from the DB and look at them - //Here is the policy object + + // Let's retrieve the policy, configurationData and actionBody from the DB and look at them + // Here is the policy object resultList = query.getResultList(); p2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results p2 = (PolicyEntity) resultList.get(0); - }else{ + } else { fail("PolicyEntityTest: No PolicyEntity DB entry found"); } - - logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB AFTER assigning configurationData*********" - + "\npolicyId2 = " + p2.getPolicyId() - + "\npolicyName2 = " + p2.getPolicyName() - + "\nversion2 = " + p2.getVersion() - + "\npolicyData2 = " + p2.getPolicyData() - + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") - + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") - + "\nscope2 = " + p2.getScope() - + "\ncreatedBy2 = " + p2.getCreatedBy() - + "\ncreatedDate2 = " + p2.getCreatedDate() - + "\ndescription2 = " + p2.getDescription() - + "\nmodifiedBy2 = " + p2.getModifiedBy() - + "\nmodifiedDate2 = " + p2.getModifiedDate() - + "\ndeleted2 = " + p2.isDeleted()); - - //And now the ConfigurationDataEntity object + + logger.debug( + "\n\n********PolicyEntityTest: PolicyEntity object after retrieving from DB AFTER assigning " + + "configurationData*********" + + "\npolicyId2 = " + p2.getPolicyId() + "\npolicyName2 = " + p2.getPolicyName() + + "\nversion2 = " + p2.getVersion() + "\npolicyData2 = " + p2.getPolicyData() + + "\nconfigurationData2 = " + + (p2.getConfigurationData() != null + ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() + : "configurationData is null") + + "\nactionBody2 = " + + (p2.getActionBodyEntity() != null + ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() + : "actionBody is null") + + "\nscope2 = " + p2.getScope() + "\ncreatedBy2 = " + p2.getCreatedBy() + "\ncreatedDate2 = " + + p2.getCreatedDate() + "\ndescription2 = " + p2.getDescription() + "\nmodifiedBy2 = " + + p2.getModifiedBy() + "\nmodifiedDate2 = " + p2.getModifiedDate() + "\ndeleted2 = " + + p2.isDeleted()); + + // And now the ConfigurationDataEntity object resultList = query2.getResultList(); c2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results c2 = (ConfigurationDataEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No ConfigurationDataEntity DB entry found"); } - - logger.debug("\n\n********PolicyEntityTest: Configuration object after retrieving from DB AFTER assigning to policy*********" - + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() - + "\nversion2 = " + c2.getVersion() - + "\nconfigType2 = " + c2.getConfigType() - + "\nconfigBody2 = " + c2.getConfigBody() - + "\ncreatedBy2 = " + c2.getCreatedBy() - + "\ncreatedDate2 = " + c2.getCreatedDate() - + "\ndescription2 = " + c2.getDescription() - + "\nmodifiedBy = " + c2.getModifiedBy() - + "\nmodifiedDate = " + c2.getModifiedDate() - + "\ndeleted2 = " + c2.isDeleted()); - - - //Get the database version of the Action Body + + logger.debug( + "\n\n********PolicyEntityTest: Configuration object after retrieving from DB AFTER assigning to " + + "policy*********" + + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() + "\nversion2 = " + c2.getVersion() + + "\nconfigType2 = " + c2.getConfigType() + "\nconfigBody2 = " + c2.getConfigBody() + + "\ncreatedBy2 = " + c2.getCreatedBy() + "\ncreatedDate2 = " + c2.getCreatedDate() + + "\ndescription2 = " + c2.getDescription() + "\nmodifiedBy = " + c2.getModifiedBy() + + "\nmodifiedDate = " + c2.getModifiedDate() + "\ndeleted2 = " + c2.isDeleted()); + + // Get the database version of the Action Body resultList = querya2.getResultList(); a2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results a2 = (ActionBodyEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No ActionBodyEntity DB entry found"); } - - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB AFTER assigning to policy *********" - + "\nactionBodyId2 = " + a2.getActionBodyId() - + "\nactionBodyVersion2 = " + a2.getVersion() - + "\nactionBody2 = " + a2.getActionBody() - + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() - + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() - + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() - + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() - + "\nactionBodyDeleted2 = " + a2.isDeleted()); - - - //****Now lets see if the orphanRemoval=true does anything useful*** - //Remove the configurationData from the policy relationship - + + logger.debug( + "\n\n********PolicyEntityTest: Local Action Body object after retrieving from DB AFTER assigning to " + + "policy *********" + + "\nactionBodyId2 = " + a2.getActionBodyId() + "\nactionBodyVersion2 = " + a2.getVersion() + + "\nactionBody2 = " + a2.getActionBody() + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() + + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() + "\nactionBodyModifiedBy2 = " + + a2.getModifiedBy() + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() + + "\nactionBodyDeleted2 = " + a2.isDeleted()); + + // ****Now lets see if the orphanRemoval=true does anything useful*** + // Remove the configurationData from the policy relationship + p1.setConfigurationData(null); - + p1.setActionBodyEntity(null); - - //flush the update to the DB + + // flush the update to the DB em.flush(); - - //Attempt to retrieve the configuration data object from the db. It should not be there - //Reusing the previous query + + // Attempt to retrieve the configuration data object from the db. It should not be there + // Reusing the previous query resultList = query2.getResultList(); c2 = null; - if(resultList.isEmpty()){ + if (resultList.isEmpty()) { logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******" + "\n Success!! No ConfigurationDataEntity DB entry found"); - - }else{ + + } else { c2 = (ConfigurationDataEntity) resultList.get(0); fail("\nPolicyEntityTest: ConfigurationDataEntity DB entry found - and none should exist" + "\nconfigurationDataId = " + c2.getConfigurationDataId()); } - - //Attempt to retrieve the actionBody data object from the db. It should not be there - //Reusing the previous query + + // Attempt to retrieve the actionBody data object from the db. It should not be there + // Reusing the previous query resultList = querya2.getResultList(); a2 = null; - if(resultList.isEmpty()){ + if (resultList.isEmpty()) { logger.debug("\n\n********PolicyEntityTest: orphanRemoval=true******" + "\n Success!! No ActionBodyEntity DB entry found"); - - }else{ + + } else { a2 = (ActionBodyEntity) resultList.get(0); - fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist" - + "\nactionBodyId = " + a2.getActionBodyId()); + fail("\nPolicyEntityTest: ActionBodyEntity DB entry found - and none should exist" + "\nactionBodyId = " + + a2.getActionBodyId()); } - - //Now lets put the configurationData and actionBody back into the policy object and see what appears - //in the DB after a flush - - //put c1 back into the persistence context since the orphanRemoval removed it. + + // Now lets put the configurationData and actionBody back into the policy object and see what appears + // in the DB after a flush + + // put c1 back into the persistence context since the orphanRemoval removed it. em.persist(c1); p1.setConfigurationData(c1); - + em.persist(a1); p1.setActionBodyEntity(a1); - + em.flush(); - - //retrieve the policy object + + // retrieve the policy object resultList = query.getResultList(); p2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results p2 = (PolicyEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest: No PolicyEntity DB entry found"); } - - //output what we policy object found - logger.debug("\n\n********PolicyEntityTest: PolicyEntity object after again adding ConfigurationDataEntity and retrieving from DB*********" - + "\npolicyId2 = " + p2.getPolicyId() - + "\npolicyName2 = " + p2.getPolicyName() - + "\nversion2 = " + p2.getVersion() - + "\npolicyData2 = " + p2.getPolicyData() - + "\nconfigurationData2 = " + (p2.getConfigurationData()!=null ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() : "configurationData is null") - + "\nactionBody2 = " + (p2.getActionBodyEntity()!=null ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() : "actionBody is null") - + "\nscope2 = " + p2.getScope() - + "\ncreatedBy2 = " + p2.getCreatedBy() - + "\ncreatedDate2 = " + p2.getCreatedDate() - + "\ndescription2 = " + p2.getDescription() - + "\nmodifiedBy2 = " + p2.getModifiedBy() - + "\nmodifiedDate2 = " + p2.getModifiedDate() - + "\ndeleted2 = " + p2.isDeleted()); - - - //now lets see if it put the configurationData c1 back into the table + + // output what we policy object found + logger.debug( + "\n\n********PolicyEntityTest: PolicyEntity object after again adding ConfigurationDataEntity " + + "and retrieving from DB*********" + "\npolicyId2 = " + p2.getPolicyId() + "\npolicyName2 = " + + p2.getPolicyName() + "\nversion2 = " + p2.getVersion() + "\npolicyData2 = " + + p2.getPolicyData() + "\nconfigurationData2 = " + + (p2.getConfigurationData() != null + ? "configurationDataId = " + p2.getConfigurationData().getConfigurationDataId() + : "configurationData is null") + + "\nactionBody2 = " + + (p2.getActionBodyEntity() != null + ? "actionBodyId = " + p2.getActionBodyEntity().getActionBodyId() + : "actionBody is null") + + "\nscope2 = " + p2.getScope() + "\ncreatedBy2 = " + p2.getCreatedBy() + "\ncreatedDate2 = " + + p2.getCreatedDate() + "\ndescription2 = " + p2.getDescription() + "\nmodifiedBy2 = " + + p2.getModifiedBy() + "\nmodifiedDate2 = " + p2.getModifiedDate() + "\ndeleted2 = " + + p2.isDeleted()); + + // now lets see if it put the configurationData c1 back into the table resultList = query2.getResultList(); c2 = null; - if(!resultList.isEmpty()){ + if (!resultList.isEmpty()) { // ignores multiple results c2 = (ConfigurationDataEntity) resultList.get(0); - }else{ + } else { fail("\nPolicyEntityTest - Check re-entry of configurationData into DB" + "No ConfigurationDataEntity DB entry found"); } - - //output what configurationData object we found - logger.debug("\n\n********PolicyEntityTest: Configuration object after re-enter into policy object and retrieving from DB *********" - + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() - + "\nversion2 = " + c2.getVersion() - + "\nconfigType2 = " + c2.getConfigType() - + "\nconfigBody2 = " + c2.getConfigBody() - + "\ncreatedBy2 = " + c2.getCreatedBy() - + "\ncreatedDate2 = " + c2.getCreatedDate() - + "\ndescription2 = " + c2.getDescription() - + "\nmodifiedBy = " + c2.getModifiedBy() - + "\nmodifiedDate = " + c2.getModifiedDate() - + "\ndeleted2 = " + c2.isDeleted()); - - //now lets see if it put the actionBody a1 back into the table - //Get the database version of the Action Body + + // output what configurationData object we found + logger.debug( + "\n\n********PolicyEntityTest: Configuration object after re-enter into policy object and retrieving " + + "from DB *********" + + "\nconfigurationDataId2 = " + c2.getConfigurationDataId() + "\nversion2 = " + c2.getVersion() + + "\nconfigType2 = " + c2.getConfigType() + "\nconfigBody2 = " + c2.getConfigBody() + + "\ncreatedBy2 = " + c2.getCreatedBy() + "\ncreatedDate2 = " + c2.getCreatedDate() + + "\ndescription2 = " + c2.getDescription() + "\nmodifiedBy = " + c2.getModifiedBy() + + "\nmodifiedDate = " + c2.getModifiedDate() + "\ndeleted2 = " + c2.isDeleted()); + + // now lets see if it put the actionBody a1 back into the table + // Get the database version of the Action Body resultList = querya2.getResultList(); - a2 = null; - if(!resultList.isEmpty()){ - // ignores multiple results - a2 = (ActionBodyEntity) resultList.get(0); - }else{ - fail("\nPolicyEntityTest - Check re-entry of actionBody into DB" - + "No ActionBodyEntity DB entry found"); - } - - logger.debug("\n\n********PolicyEntityTest: Local Action Body object after re-enter into policy object and retrieving from DB *********" - + "\nactionBodyId2 = " + a2.getActionBodyId() - + "\nactionBodyVersion2 = " + a2.getVersion() - + "\nactionBody2 = " + a2.getActionBody() - + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() - + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() - + "\nactionBodyModifiedBy2 = " + a2.getModifiedBy() - + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() - + "\nactionBodyDeleted2 = " + a2.isDeleted()); - - //I want to save all the above in the DB - try{ + a2 = null; + if (!resultList.isEmpty()) { + // ignores multiple results + a2 = (ActionBodyEntity) resultList.get(0); + } else { + fail("\nPolicyEntityTest - Check re-entry of actionBody into DB" + "No ActionBodyEntity DB entry found"); + } + + logger.debug( + "\n\n********PolicyEntityTest: Local Action Body object after re-enter into policy object and " + + "retrieving from DB *********" + + "\nactionBodyId2 = " + a2.getActionBodyId() + "\nactionBodyVersion2 = " + a2.getVersion() + + "\nactionBody2 = " + a2.getActionBody() + "\nactionBodyCeatedBy2 = " + a2.getCreatedBy() + + "\nactionBodyCreatedDate2 = " + a2.getCreatedDate() + "\nactionBodyModifiedBy2 = " + + a2.getModifiedBy() + "\nactionBodyModifiedDate2 = " + a2.getModifiedDate() + + "\nactionBodyDeleted2 = " + a2.isDeleted()); + + // I want to save all the above in the DB + try { et.commit(); logger.debug("\n\n***********PolicyEntityTest: et.commit Succeeded********"); - }catch(Exception e){ - logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********" - + "\nTRANSACTION ROLLBACK " + } catch (Exception e) { + logger.debug("\n\n***********PolicyEntityTest: et.commit Failed********" + "\nTRANSACTION ROLLBACK " + "\n with exception: " + e); } @@ -598,206 +559,184 @@ public class PolicyEntityTest { EntityTransaction et2 = em.getTransaction(); et2.begin(); - - //Let's test if the PolicyEntity uniqueConstraint for policyName and scopeId hold + + // Let's test if the PolicyEntity uniqueConstraint for policyName and scopeId hold PolicyEntity p3 = new PolicyEntity(); em.persist(p3); - - //first let's assure that you can save with the same name but a different scope + // first let's assure that you can save with the same name but a different scope p3.setPolicyName(p1.getPolicyName()); p3.setScope("mckiou.kevin.kory"); em.flush(); logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" - + "\nSuccess! PolicyEntity uniqueness constraint allowed " - + "\n policyId1 " + p1.getPolicyId() - + "\n policyName1 " + p1.getPolicyName() - + "\n scope1 = " + p1.getScope() - + "\n policyId3 " + p3.getPolicyId() - + "\n policyName3 " + p3.getPolicyName() - + "\n scope3 = " + p3.getScope()); - - //Assert that the policyIds are NOT the same to show that the automatic sequencing is working - assert(p1.getPolicyId() != p3.getPolicyId()); - - try{ - //Now set the scope the same to verify the uniqueness constraint will be enforced + + "\nSuccess! PolicyEntity uniqueness constraint allowed " + "\n policyId1 " + p1.getPolicyId() + + "\n policyName1 " + p1.getPolicyName() + "\n scope1 = " + p1.getScope() + "\n policyId3 " + + p3.getPolicyId() + "\n policyName3 " + p3.getPolicyName() + "\n scope3 = " + p3.getScope()); + + // Assert that the policyIds are NOT the same to show that the automatic sequencing is working + assert (p1.getPolicyId() != p3.getPolicyId()); + + try { + // Now set the scope the same to verify the uniqueness constraint will be enforced p3.setScope(p1.getScope()); em.flush(); logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" - + "\nFailed! PolicyEntity Uniqueness constraint FAILED and DID allow " - + "\n policyId1 " + p1.getPolicyId() - + "\n policyName1 " + p1.getPolicyName() - + "\n scope1 = " + p1.getScope() - + "\n policyId3 " + p3.getPolicyId() - + "\n policyName3 " + p3.getPolicyName() - + "\n scope3 = " + p3.getScope());; - } - catch(Exception e){ - //Success + + "\nFailed! PolicyEntity Uniqueness constraint FAILED and DID allow " + "\n policyId1 " + + p1.getPolicyId() + "\n policyName1 " + p1.getPolicyName() + "\n scope1 = " + p1.getScope() + + "\n policyId3 " + p3.getPolicyId() + "\n policyName3 " + p3.getPolicyName() + + "\n scope3 = " + + p3.getScope());; + } catch (Exception e) { + // Success logger.debug("\n\n***********PolicyEntityTest: PolicyEntity Unique test for policyName and scope********" - + "\nSuccess! PolicyEntity Uniqueness constraint SUCCEEDED and did NOT allow " - + "\n policyId1 " + p1.getPolicyId() - + "\n policyName1 " + p1.getPolicyName() - + "\n scope1 = " + p1.getScope() - + "\n policyId3 " + p3.getPolicyId() - + "\n policyName3 " + p3.getPolicyName() - + "\n scope3 = " + p3.getScope() - + "\n with excpetion: " + e); + + "\nSuccess! PolicyEntity Uniqueness constraint SUCCEEDED and did NOT allow " + "\n policyId1 " + + p1.getPolicyId() + "\n policyName1 " + p1.getPolicyName() + "\n scope1 = " + p1.getScope() + + "\n policyId3 " + p3.getPolicyId() + "\n policyName3 " + p3.getPolicyName() + + "\n scope3 = " + + p3.getScope() + "\n with excpetion: " + e); } - - try{ + try { et2.commit(); logger.debug("\n\n***********PolicyEntityTest: et2.commit Succeeded********"); - }catch(Exception e){ - logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********" - + "\nTRANSACTION ROLLBACK " + } catch (Exception e) { + logger.debug("\n\n***********PolicyEntityTest: et2.commit Failed********" + "\nTRANSACTION ROLLBACK " + "\n with exception: " + e); } - - //****************Test the PolicyDBDaoEntity************************ - - //Create a transaction + + // ****************Test the PolicyDBDaoEntity************************ + + // Create a transaction EntityTransaction et3 = em.getTransaction(); et3.begin(); - - //create one + + // create one PolicyDBDaoEntity pe1 = new PolicyDBDaoEntity(); em.persist(pe1); - + pe1.setDescription("This is pe1"); - + pe1.setPolicyDBDaoUrl("http://123.45.2.456:2345"); - - //push it to the DB + + // push it to the DB em.flush(); - - //create another + + // create another PolicyDBDaoEntity pe2 = new PolicyDBDaoEntity(); em.persist(pe2); - + pe2.setDescription("This is pe2"); - + pe2.setPolicyDBDaoUrl("http://789.01.2.345:2345"); - - //Print them to the log before flushing + + // Print them to the log before flushing logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects before flush********" - + "\n policyDBDaoUrl-1 = " + pe1.getPolicyDBDaoUrl() - + "\n description-1 = " + pe1.getDescription() - + "\n createdDate-1 = " + pe1.getCreatedDate() - + "\n modifiedDate-1 " + pe1.getModifiedDate() - + "\n*****************************************" - + "\n policyDBDaoUrl-2 = " + pe2.getPolicyDBDaoUrl() - + "\n description-2 = " + pe2.getDescription() - + "\n createdDate-2 = " + pe2.getCreatedDate() - + "\n modifiedDate-2 " + pe2.getModifiedDate() - ); - - //push it to the DB + + "\n policyDBDaoUrl-1 = " + pe1.getPolicyDBDaoUrl() + "\n description-1 = " + pe1.getDescription() + + "\n createdDate-1 = " + pe1.getCreatedDate() + "\n modifiedDate-1 " + pe1.getModifiedDate() + + "\n*****************************************" + "\n policyDBDaoUrl-2 = " + pe2.getPolicyDBDaoUrl() + + "\n description-2 = " + pe2.getDescription() + "\n createdDate-2 = " + pe2.getCreatedDate() + + "\n modifiedDate-2 " + pe2.getModifiedDate()); + + // push it to the DB em.flush(); - - //Now let's retrieve them from the DB using the named query - + + // Now let's retrieve them from the DB using the named query + resultList = em.createNamedQuery("PolicyDBDaoEntity.findAll").getResultList(); PolicyDBDaoEntity pex = null; PolicyDBDaoEntity pey = null; - if(!resultList.isEmpty()){ - if (resultList.size() != 2){ - fail("\nPolicyEntityTest: Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 2"); + if (!resultList.isEmpty()) { + if (resultList.size() != 2) { + fail("\nPolicyEntityTest: Number of PolicyDBDaoEntity entries = " + resultList.size() + + " instead of 2"); } - for(Object policyDBDaoEntity: resultList){ - PolicyDBDaoEntity pdbdao = (PolicyDBDaoEntity)policyDBDaoEntity; - if(pdbdao.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){ + for (Object policyDBDaoEntity : resultList) { + PolicyDBDaoEntity pdbdao = (PolicyDBDaoEntity) policyDBDaoEntity; + if (pdbdao.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")) { pex = pdbdao; - }else if(pdbdao.getPolicyDBDaoUrl().equals("http://789.01.2.345:2345")){ + } else if (pdbdao.getPolicyDBDaoUrl().equals("http://789.01.2.345:2345")) { pey = pdbdao; } } - //Print them to the log before flushing + // Print them to the log before flushing logger.debug("\n\n***********PolicyEntityTest: PolicyDBDaoEntity objects retrieved from DB********" - + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() - + "\n description-x = " + pex.getDescription() - + "\n createdDate-x = " + pex.getCreatedDate() - + "\n modifiedDate-x " + pex.getModifiedDate() - + "\n*****************************************" - + "\n policyDBDaoUrl-y = " + pey.getPolicyDBDaoUrl() - + "\n description-y = " + pey.getDescription() - + "\n createdDate-y = " + pey.getCreatedDate() - + "\n modifiedDate-y " + pey.getModifiedDate() - ); - //Verify the retrieved objects are the same as the ones we stored in the DB - if(pex.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")){ - assertSame(pe1,pex); - assertSame(pe2,pey); - }else{ - assertSame(pe2,pex); - assertSame(pe1,pey); + + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() + "\n description-x = " + + pex.getDescription() + "\n createdDate-x = " + pex.getCreatedDate() + "\n modifiedDate-x " + + pex.getModifiedDate() + "\n*****************************************" + + "\n policyDBDaoUrl-y = " + + pey.getPolicyDBDaoUrl() + "\n description-y = " + pey.getDescription() + + "\n createdDate-y = " + + pey.getCreatedDate() + "\n modifiedDate-y " + pey.getModifiedDate()); + // Verify the retrieved objects are the same as the ones we stored in the DB + if (pex.getPolicyDBDaoUrl().equals("http://123.45.2.456:2345")) { + assertSame(pe1, pex); + assertSame(pe2, pey); + } else { + assertSame(pe2, pex); + assertSame(pe1, pey); } - - }else{ + + } else { fail("\nPolicyEntityTest: No PolicyDBDaoEntity DB entry found"); } - - //Now let's see if we can do an update on the PolicyDBDaoEntity which we retrieved. - //em.persist(pex); + + // Now let's see if we can do an update on the PolicyDBDaoEntity which we retrieved. + // em.persist(pex); pex.setDescription("This is pex"); em.flush(); - - //retrieve it + + // retrieve it Query createPolicyQuery = em.createQuery("SELECT p FROM PolicyDBDaoEntity p WHERE p.description=:desc"); resultList = createPolicyQuery.setParameter("desc", "This is pex").getResultList(); PolicyDBDaoEntity pez = null; - - if(!resultList.isEmpty()){ - if (resultList.size() != 1){ - fail("\nPolicyEntityTest: Update Test - Number of PolicyDBDaoEntity entries = " + resultList.size() + " instead of 1"); + + if (!resultList.isEmpty()) { + if (resultList.size() != 1) { + fail("\nPolicyEntityTest: Update Test - Number of PolicyDBDaoEntity entries = " + resultList.size() + + " instead of 1"); } pez = (PolicyDBDaoEntity) resultList.get(0); - //Print them to the log before flushing - logger.debug("\n\n***********PolicyEntityTest: Update Test - PolicyDBDaoEntity objects retrieved from DB********" - + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() - + "\n description-x = " + pex.getDescription() - + "\n createdDate-x = " + pex.getCreatedDate() - + "\n modifiedDate-x " + pex.getModifiedDate() - + "\n*****************************************" - + "\n policyDBDaoUrl-z = " + pez.getPolicyDBDaoUrl() - + "\n description-z = " + pez.getDescription() - + "\n createdDate-z = " + pez.getCreatedDate() - + "\n modifiedDate-z " + pez.getModifiedDate() - ); - //Verify the retrieved objects are the same as the ones we stored in the DB - assertSame(pex,pez); - }else{ + // Print them to the log before flushing + logger.debug( + "\n\n***********PolicyEntityTest: Update Test - PolicyDBDaoEntity objects retrieved from " + + "DB********" + + "\n policyDBDaoUrl-x = " + pex.getPolicyDBDaoUrl() + "\n description-x = " + + pex.getDescription() + "\n createdDate-x = " + pex.getCreatedDate() + + "\n modifiedDate-x " + pex.getModifiedDate() + + "\n*****************************************" + "\n policyDBDaoUrl-z = " + + pez.getPolicyDBDaoUrl() + "\n description-z = " + pez.getDescription() + + "\n createdDate-z = " + pez.getCreatedDate() + "\n modifiedDate-z " + + pez.getModifiedDate()); + // Verify the retrieved objects are the same as the ones we stored in the DB + assertSame(pex, pez); + } else { fail("\nPolicyEntityTest: Update Test - No PolicyDBDaoEntity DB updated entry found"); } - - //Clean up the DB + + // Clean up the DB em.createQuery("DELETE FROM PolicyDBDaoEntity").executeUpdate(); em.createQuery("DELETE FROM PolicyEntity").executeUpdate(); em.createQuery("DELETE FROM ConfigurationDataEntity").executeUpdate(); em.createQuery("DELETE FROM ActionBodyEntity").executeUpdate(); - - //Wrap up the transaction - try{ + + // Wrap up the transaction + try { et3.commit(); logger.debug("\n\n***********PolicyEntityTest: et3.commit Succeeded********"); - }catch(Exception e){ - logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********" - + "\nTRANSACTION ROLLBACK " + } catch (Exception e) { + logger.debug("\n\n***********PolicyEntityTest: et3.commit Failed********" + "\nTRANSACTION ROLLBACK " + "\n with exception: " + e); } - - - //Tidy up + + // Tidy up em.close(); } - + } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java index cd6bf021d..81f9fae9d 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/model/RemoveGroupPolicyTest.java @@ -21,7 +21,9 @@ package org.onap.policy.pap.xacml.rest.model; import static org.junit.Assert.assertEquals; + import com.att.research.xacml.api.pap.PDPPolicy; + import org.junit.Test; import org.onap.policy.xacml.std.pap.StdPDPGroup; import org.onap.policy.xacml.std.pap.StdPDPPolicy; diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java index ba400dfc0..72d492620 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/ImportServiceTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -21,11 +21,14 @@ package org.onap.policy.pap.xacml.rest.service; import static org.junit.Assert.assertEquals; + +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; + import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; + import org.junit.Test; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; public class ImportServiceTest { @Test diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java index c90e59bf6..a4ee0ca77 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/service/MetricServiceTest.java @@ -2,7 +2,7 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -22,8 +22,11 @@ package org.onap.policy.pap.xacml.rest.service; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.when; + import com.mockrunner.mock.web.MockHttpServletResponse; + import javax.servlet.http.HttpServletResponse; + import org.junit.Test; import org.junit.runner.RunWith; import org.onap.policy.pap.xacml.rest.XACMLPapServlet; @@ -42,6 +45,6 @@ public class MetricServiceTest { MockHttpServletResponse response = new MockHttpServletResponse(); MetricService.doGetPolicyMetrics(response); - assertEquals(response.getStatusCode(), HttpServletResponse.SC_BAD_REQUEST); + assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusCode()); } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java index ad8f86c59..6c83dcd1c 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JPAUtilsTest.java @@ -22,8 +22,9 @@ package org.onap.policy.pap.xacml.rest.util; -import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; + import org.junit.BeforeClass; import org.junit.Test; import org.onap.policy.pap.xacml.rest.components.PolicyDBDaoTest; @@ -41,7 +42,7 @@ public class JPAUtilsTest { // Test lockdown JPAUtils utils = JPAUtils.getJPAUtilsInstance(); - assertEquals(utils.dbLockdownIgnoreErrors(), false); + assertFalse(utils.dbLockdownIgnoreErrors()); utils.dbLockdown(); fail("Expecting an exception"); } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java index e3a575456..fd96451f3 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/rest/util/JsonMessageTest.java @@ -2,16 +2,16 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 AT&T Intellectual Property. All rights reserved. * ================================================================================ * Modifications Copyright (C) 2019 Samsung * ================================================================================ * 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. @@ -23,6 +23,7 @@ package org.onap.policy.pap.xacml.rest.util; import static org.junit.Assert.assertEquals; + import org.junit.Test; public class JsonMessageTest { diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java index cbe9ff250..f84f41e5f 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/AuthenticationServiceTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,11 +17,14 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.restAuth; import static org.junit.Assert.assertEquals; + import java.io.UnsupportedEncodingException; import java.util.Base64; + import org.junit.Test; import org.onap.policy.pap.xacml.restAuth.AuthenticationService; @@ -44,8 +47,7 @@ public class AuthenticationServiceTest { // Restore the original system property if (oldProperty != null) { System.setProperty(systemKey, oldProperty); - } - else { + } else { System.clearProperty(systemKey); } } diff --git a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java index f1554e84c..c358a85ad 100644 --- a/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java +++ b/ONAP-PAP-REST/src/test/java/org/onap/policy/pap/xacml/restAuth/PAPAuthenticationFilterTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-PDP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -17,11 +17,15 @@ * limitations under the License. * ============LICENSE_END========================================================= */ + package org.onap.policy.pap.xacml.restAuth; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; +import com.mockrunner.mock.web.MockHttpServletRequest; +import com.mockrunner.mock.web.MockHttpServletResponse; + import java.io.IOException; import javax.servlet.FilterChain; @@ -34,9 +38,6 @@ import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; -import com.mockrunner.mock.web.MockHttpServletRequest; -import com.mockrunner.mock.web.MockHttpServletResponse; - public class PAPAuthenticationFilterTest { private HttpServletRequest request = null; @@ -47,7 +48,7 @@ public class PAPAuthenticationFilterTest { private PAPAuthenticationFilter papFilter; @Before - public void setUp(){ + public void setUp() { // Set the system property temporarily oldProperty = System.getProperty(systemKey); System.setProperty(systemKey, "xacml.pap.properties"); @@ -74,8 +75,7 @@ public class PAPAuthenticationFilterTest { try { filter.destroy(); filter.init(null); - } - catch (Exception ex) { + } catch (Exception ex) { fail("Not expecting any exceptions."); } } @@ -89,7 +89,7 @@ public class PAPAuthenticationFilterTest { callDoFilter(); } - public void callDoFilter(){ + public void callDoFilter() { try { papFilter.doFilter(request, response, filter); } catch (Exception e) { @@ -98,7 +98,7 @@ public class PAPAuthenticationFilterTest { } @Test - public void testOnPassingInvalidParamters(){ + public void testOnPassingInvalidParamters() { Mockito.when(request.getRequestURI()).thenReturn("/pap/"); Mockito.when(request.getHeader("Authorization")).thenReturn("Basic dGVzdHBhcDphbHBoYTE789=="); try { @@ -110,7 +110,7 @@ public class PAPAuthenticationFilterTest { } @After - public void reset(){ + public void reset() { // Restore the original system property if (oldProperty != null) { System.setProperty(systemKey, oldProperty); diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java index d1da554d9..d09059978 100644 --- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/api/utils/test/PolicyApiUtilsTest.java @@ -28,7 +28,6 @@ import static org.junit.Assert.assertTrue; import javax.json.Json; import javax.json.JsonArray; import javax.json.JsonObject; -import org.json.JSONObject; import org.junit.Test; import org.onap.policy.pdp.rest.api.utils.PolicyApiUtils; diff --git a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java index 261226527..190f93aa7 100644 --- a/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java +++ b/ONAP-PDP-REST/src/test/java/org/onap/policy/pdp/rest/notifications/test/NotificationTest.java @@ -23,8 +23,6 @@ package org.onap.policy.pdp.rest.notifications.test; import static org.junit.Assert.assertEquals; import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; import java.util.List; import org.junit.Test; import org.onap.policy.api.NotificationType; diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java index 0a3f46c78..97e6e9ef6 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/adapter/PolicyRestAdapter.java @@ -1154,4 +1154,55 @@ public class PolicyRestAdapter { public void setUiJsonBody(String uiJsonBody) { this.uiJsonBody = uiJsonBody; } + + public boolean setupUsingAttribute(String attributeId, String value) { + switch (attributeId) { + case "ONAPName": + this.setOnapName(value); + OnapName tempOnapName = new OnapName(); + tempOnapName.setOnapName(value); + this.setOnapNameField(tempOnapName); + return true; + case "RiskType": + this.setRiskType(value); + return true; + case "RiskLevel": + this.setRiskLevel(value); + return true; + case "guard": + this.setGuard(value); + return true; + case "ConfigName": + this.setConfigName(value); + return true; + case "uuid": + this.setUuid(value); + return true; + case "location": + this.setLocation(value); + return true; + case "TTLDate": + if (!value.contains("NA")) { + this.setTtlDate(PolicyRestAdapter.convertDate(value)); + return true; + } + return false; + default: + return false; + } + } + + /** + * Function to convert date. + * + * @param dateTimeToLive input date value. + * @return + */ + private static String convertDate(String dateTimeToLive) { + String formatDate = null; + if (dateTimeToLive.contains("-")) { + formatDate = dateTimeToLive.replace("-", "/"); + } + return formatDate; + } } diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaults.java b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaults.java index 905555120..5098628b0 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaults.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/jpa/MicroserviceHeaderdeFaults.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -39,8 +39,6 @@ import javax.persistence.Table; public class MicroserviceHeaderdeFaults implements Serializable { private static final long serialVersionUID = 1L; - private static String domain; - @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="id") diff --git a/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java b/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java index 50e30f05b..f509abdbb 100644 --- a/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java +++ b/ONAP-REST/src/main/java/org/onap/policy/rest/util/ParserException.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP-REST * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -19,12 +19,17 @@ */ package org.onap.policy.rest.util; -public class ParserException extends Exception{ - String message; - ParserException(String message) { +public class ParserException extends Exception { + private static final long serialVersionUID = -1166704711958410424L; + + final String message; + + ParserException(String message) { this.message = message; - } - public String getMessage(){ - return message ; - } + } + + @Override + public String getMessage() { + return message; + } }
\ No newline at end of file diff --git a/ONAP-REST/src/test/java/org/onap/policy/rest/adapter/PolicyRestAdapterTest.java b/ONAP-REST/src/test/java/org/onap/policy/rest/adapter/PolicyRestAdapterTest.java index 971614359..860e08d93 100644 --- a/ONAP-REST/src/test/java/org/onap/policy/rest/adapter/PolicyRestAdapterTest.java +++ b/ONAP-REST/src/test/java/org/onap/policy/rest/adapter/PolicyRestAdapterTest.java @@ -2,14 +2,14 @@ * ============LICENSE_START======================================================= * ONAP Policy Engine * ================================================================================ - * Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2018-2019 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. @@ -19,6 +19,8 @@ */ package org.onap.policy.rest.adapter; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; @@ -257,4 +259,26 @@ public class PolicyRestAdapterTest { adapter.setSupressionType("Test"); assertTrue("Test".equals(adapter.getSupressionType())); } + + @Test + public void testPublic() { + PolicyRestAdapter adapter = new PolicyRestAdapter(); + adapter.setupUsingAttribute("ONAPName", "onapvalue"); + adapter.setupUsingAttribute("RiskType", "riskvalue"); + adapter.setupUsingAttribute("RiskLevel", "risklevel"); + adapter.setupUsingAttribute("guard", "guardvalue"); + adapter.setupUsingAttribute("ConfigName", "configvalue"); + adapter.setupUsingAttribute("uuid", "uuidvalue"); + adapter.setupUsingAttribute("location", "locationvalue"); + assertEquals("riskvalue", adapter.getRiskType()); + assertEquals("risklevel", adapter.getRiskLevel()); + assertEquals("guardvalue", adapter.getGuard()); + assertEquals("onapvalue", adapter.getOnapName()); + assertEquals("onapvalue", adapter.getOnapNameField().getOnapName()); + assertEquals("uuidvalue", adapter.getUuid()); + assertEquals("locationvalue", adapter.getLocation()); + assertEquals("configvalue", adapter.getConfigName()); + + assertFalse(adapter.setupUsingAttribute("foobar", "foo")); + } } diff --git a/ONAP-SDK-APP/src/test/java/org/onap/portalapp/scheduler/RegisterTest.java b/ONAP-SDK-APP/src/test/java/org/onap/portalapp/scheduler/RegisterTest.java index 675a87e43..68454112d 100644 --- a/ONAP-SDK-APP/src/test/java/org/onap/portalapp/scheduler/RegisterTest.java +++ b/ONAP-SDK-APP/src/test/java/org/onap/portalapp/scheduler/RegisterTest.java @@ -40,8 +40,8 @@ public class RegisterTest { triggers.add(trigger); register.setScheduleTriggers(triggers); - assertEquals(register.getScheduleTriggers(), triggers); - assertEquals(register.getTriggers().length, 1); + assertEquals(triggers, register.getScheduleTriggers()); + assertEquals(1, register.getTriggers().length); } @Test(expected = NullPointerException.class) @@ -54,7 +54,6 @@ public class RegisterTest { @Test(expected = NullPointerException.class) public void testRegisterNegativeCase2() { // Setup test data - String value = "testVal"; Register register = new Register(); List<Trigger> triggers = new ArrayList<Trigger>(); register.setScheduleTriggers(triggers); diff --git a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java index 0003e12c6..e0ee60ade 100644 --- a/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java +++ b/ONAP-XACML/src/main/java/org/onap/policy/xacml/util/XACMLPolicyScanner.java @@ -7,9 +7,9 @@ * 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. @@ -37,8 +37,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; import org.onap.policy.common.logging.eelf.MessageCodes; import org.onap.policy.common.logging.eelf.PolicyLogger; @@ -73,18 +71,18 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.VariableDefinitionType; /** * class XACMLPolicyScanner - * + * * This class traverses the hierarchy of a XACML 3.0 policy. You can optionally pass a Callback class - * and override any desired methods to retrieve information from a policy. - * + * and override any desired methods to retrieve information from a policy. + * * */ public class XACMLPolicyScanner { - + private static final Log logger = LogFactory.getLog(XACMLPolicyScanner.class); private Object policyObject = null; private Callback callback = null; - + public XACMLPolicyScanner(Path filename, Callback callback) { try (InputStream is = Files.newInputStream(filename)) { this.policyObject = XACMLPolicyScanner.readPolicy(is); @@ -93,7 +91,7 @@ public class XACMLPolicyScanner { } this.callback = callback; } - + public XACMLPolicyScanner(InputStream filename, Callback callback) { try (InputStream is = filename) { this.policyObject = XACMLPolicyScanner.readPolicy(is); @@ -102,37 +100,37 @@ public class XACMLPolicyScanner { } this.callback = callback; } - + public XACMLPolicyScanner(PolicySetType policySet, Callback callback) { this.policyObject = policySet; this.callback = callback; } - + public XACMLPolicyScanner(PolicySetType policySet) { this(policySet, null); } - + public XACMLPolicyScanner(PolicyType policy, Callback callback) { this.policyObject = policy; this.callback = callback; } - + public XACMLPolicyScanner(PolicyType policy) { this(policy, null); } - + /** * Sets the callback interface to be used. - * + * * @param cb */ public void setCallback(Callback cb) { this.callback = cb; } - + /** * Saves the given callback object then calls the scan() method. - * + * * @param cb * @return */ @@ -140,11 +138,11 @@ public class XACMLPolicyScanner { this.callback = cb; return this.scan(); } - + /** - * + * * This begins the scanning of the contained object. - * + * * @return - The PolicySet/Policy that was scanned. */ public Object scan() { @@ -166,10 +164,10 @@ public class XACMLPolicyScanner { } return this.policyObject; } - + /** * This performs the scan of a PolicySet - * + * * @param parent - Its parent PolicySet. Can be null if this is the root. * @param policySet - The PolicySet object. * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. @@ -203,7 +201,7 @@ public class XACMLPolicyScanner { // List<JAXBElement<?>> list = policySet.getPolicySetOrPolicyOrPolicySetIdReference(); for (JAXBElement<?> element: list) { - if ("PolicySet".equals(element.getName().getLocalPart()) && + if ("PolicySet".equals(element.getName().getLocalPart()) && this.scanPolicySet(policySet, (PolicySetType)element.getValue()) == CallbackResult.STOP) { return CallbackResult.STOP; } else if ("Policy".equals(element.getName().getLocalPart()) && @@ -218,11 +216,11 @@ public class XACMLPolicyScanner { } return CallbackResult.CONTINUE; } - + /** - * + * * This performs scanning of the Policy object. - * + * * @param parent - The parent PolicySet of the policy. This can be null if this is a root Policy. * @param policy - The policy being scanned. * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. @@ -292,10 +290,10 @@ public class XACMLPolicyScanner { } return CallbackResult.CONTINUE; } - + /** * Scans the given target for attributes. Its sole purpose is to return attributes found. - * + * * @param parent - The parent PolicySet/Policy/Rule for the target. * @param target - The target. * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. @@ -355,10 +353,10 @@ public class XACMLPolicyScanner { } return CallbackResult.CONTINUE; } - + /** * Scan the list of obligations. - * + * * @param parent - The parent PolicySet/Policy/Rule for the obligation. * @param obligationExpressionsType - All the obligation expressions. * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. @@ -398,9 +396,9 @@ public class XACMLPolicyScanner { } /** - * + * * Scans the list of advice expressions returning each individually. - * + * * @param parent - The parent PolicySet/Policy/Rule for the advice. * @param adviceExpressionstype - The list of advice expressions. * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. @@ -437,10 +435,10 @@ public class XACMLPolicyScanner { } return CallbackResult.CONTINUE; } - + /** * Scans the list of variable definitions. - * + * * @param policy - Policy object containing the variable definition. * @param list - List of variable definitions. * @return CallbackResult - CONTINUE to continue, STOP to terminate scanning. @@ -454,13 +452,13 @@ public class XACMLPolicyScanner { return CallbackResult.STOP; } } - + return CallbackResult.CONTINUE; } - + /** * Scans the list of conditions. - * + * * @param rule * @param condition * @return @@ -471,13 +469,13 @@ public class XACMLPolicyScanner { } return CallbackResult.CONTINUE; } - + /** * Reads the XACML XML policy file in and returns the version contained in the root Policy/PolicySet element. - * + * * @param policy - The policy file. * @return - The version string from the file (uninterpreted) - * @throws IOException + * @throws IOException */ public static String getVersion(Path policy) throws IOException { Object data = null; @@ -493,10 +491,10 @@ public class XACMLPolicyScanner { } return getVersion(data); } - + /** * Reads the Policy/PolicySet element object and returns its current version. - * + * * @param data - Either a PolicySet or Policy XACML type object. * @return - The integer version value. -1 if it doesn't exist or was un-parsable. */ @@ -524,10 +522,10 @@ public class XACMLPolicyScanner { } return null; } - + /** * Returns the Policy or PolicySet ID. - * + * * @param data - A XACML 3.0 Policy or PolicySet element object. * @return The policy/policyset's policy ID */ @@ -541,7 +539,7 @@ public class XACMLPolicyScanner { return null; } } - + public static List<String> getCreatedByModifiedBy(Path policyPath) throws IOException{ String createdBy = ""; String modifiedBy= ""; @@ -560,7 +558,7 @@ public class XACMLPolicyScanner { } return Arrays.asList(createdBy, modifiedBy); } - + //get the Created Name of the User on reading the Xml file public static String getCreatedBy(Path policyPath) throws IOException{ String userId = ""; @@ -577,7 +575,7 @@ public class XACMLPolicyScanner { } return userId; } - + //get the Modified Name of the User on reading the Xml file public static String getModifiedBy(Path policyPath) throws IOException{ String modifiedBy = ""; @@ -597,7 +595,7 @@ public class XACMLPolicyScanner { /** * readPolicy - does the work to read in policy data from a file. - * + * * @param policy - The path to the policy file. * @return - The policy data object. This *should* be either a PolicySet or a Policy. */ diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java index e9190968d..139b2b87f 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AdminTabController.java @@ -52,7 +52,6 @@ import org.springframework.web.servlet.ModelAndView; public class AdminTabController extends RestrictedBaseController { private static final Logger LOGGER = FlexLogger.getLogger(AdminTabController.class); - private static final String CHARACTER_ENCODING = "UTF-8"; private static CommonClassDao commonClassDao; @@ -107,8 +106,8 @@ public class AdminTabController extends RestrictedBaseController { method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public ModelAndView saveAdminTabLockdownValue(HttpServletRequest request, HttpServletResponse response) throws IOException { - response.setCharacterEncoding(CHARACTER_ENCODING); - request.setCharacterEncoding(CHARACTER_ENCODING); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); try { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -124,7 +123,7 @@ public class AdminTabController extends RestrictedBaseController { globalRole.setRole("super-admin"); commonClassDao.update(globalRole); - response.setContentType("application / json"); + response.setContentType(PolicyUtils.APPLICATION_JSON); String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class)); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java index b5e17f2e0..b26709ff4 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/AutoPushController.java @@ -79,7 +79,6 @@ import org.springframework.web.servlet.ModelAndView; public class AutoPushController extends RestrictedBaseController { private static final Logger logger = FlexLogger.getLogger(AutoPushController.class); - private static final String UTF8 = "UTF-8"; @Autowired CommonClassDao commonClassDao; @@ -194,6 +193,11 @@ public class AutoPushController extends RestrictedBaseController { public ModelAndView pushPolicyToPDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // ArrayList<Object> selectedPdps = new ArrayList<>(); ArrayList<String> selectedPoliciesInUI = new ArrayList<>(); PolicyController controller = getPolicyControllerInstance(); @@ -333,18 +337,12 @@ public class AutoPushController extends RestrictedBaseController { currentPoliciesInGroup.addAll(selectedPolicies); updatedGroupObject.setPolicies(currentPoliciesInGroup); this.container.updateGroup(updatedGroupObject, userId); - - response.setCharacterEncoding(UTF8); - response.setContentType("application / json"); - request.setCharacterEncoding(UTF8); - + response.setContentType(PolicyUtils.APPLICATION_JSON); refreshGroups(); response.getWriter().write(new JSONObject( new JsonMessage(mapper.writeValueAsString(groups))).toString()); } } catch (Exception e) { - response.setCharacterEncoding(UTF8); - request.setCharacterEncoding(UTF8); logger.error(e); response.getWriter().write(PolicyUtils.CATCH_EXCEPTION); } @@ -358,6 +356,11 @@ public class AutoPushController extends RestrictedBaseController { @RequestMapping(value = {"/auto_Push/remove_GroupPolicies.htm"}, method = {RequestMethod.POST}) public ModelAndView removePDPGroup(HttpServletRequest request, HttpServletResponse response) throws IOException { try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // PolicyController controller = getPolicyControllerInstance(); this.container = new PDPGroupContainer(controller.getPapEngine()); ObjectMapper mapper = new ObjectMapper(); @@ -390,15 +393,11 @@ public class AutoPushController extends RestrictedBaseController { this.container.updateGroup(updatedGroupObject); } - response.setCharacterEncoding(UTF8); - response.setContentType("application / json"); - request.setCharacterEncoding(UTF8); + response.setContentType(PolicyUtils.APPLICATION_JSON); refreshGroups(); response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); } catch (Exception e) { - response.setCharacterEncoding(UTF8); - request.setCharacterEncoding(UTF8); logger.error(e); response.getWriter().write(PolicyUtils.CATCH_EXCEPTION); } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java index 1adeb6d96..244b7fd95 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSParamController.java @@ -64,6 +64,7 @@ import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.BRMSParamTemplate; import org.onap.policy.rest.jpa.PolicyEntity; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.beans.factory.annotation.Autowired; @@ -244,10 +245,14 @@ public class CreateBRMSParamController extends RestrictedBaseController { dynamicLayoutMap.put(caption, type); } - /* + /** + * prePopulateBRMSParamPolicyData. * When the User Click Edit or View Policy the following method will get invoked for setting the data to * PolicyRestAdapter. - * Which is used to bind the data in GUI + * Which is used to bind the data in GUI. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity */ public void prePopulateBRMSParamPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { dynamicLayoutMap = new HashMap<>(); @@ -351,20 +356,7 @@ public class CreateBRMSParamController extends RestrictedBaseController { String value = (String) attributeValue.getContent().get(0); AttributeDesignatorType designator = match.getAttributeDesignator(); String attributeId = designator.getAttributeId(); - if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } - if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } - if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } + policyAdapter.setupUsingAttribute(attributeId, value); } } @@ -535,9 +527,9 @@ public class CreateBRMSParamController extends RestrictedBaseController { // Replacing the value with the inputs provided by the user in the editor. body = matcher.replaceAll(copyMap.get(input)); } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); response.getWriter().write(new JSONObject("{policyData: " + mapper.writeValueAsString(body) + "}").toString()); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java index 214cb3244..487165b56 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateBRMSRawController.java @@ -36,7 +36,6 @@ import oasis.names.tc.xacml._3_0.core.schema.wd_17.AdviceExpressionsType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeAssignmentExpressionType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; @@ -53,6 +52,12 @@ public class CreateBRMSRawController { protected PolicyRestAdapter policyAdapter = null; + /** + * prePopulateBRMSRawPolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { @@ -97,21 +102,8 @@ public class CreateBRMSRawController { .forEach(match -> { // Under the match we have attribute value and // attributeDesignator. So,finally down to the actual attribute. - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } else if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } else if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); })); } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java index 9f19e4c71..a7a03c021 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopFaultController.java @@ -39,8 +39,6 @@ import lombok.Getter; import lombok.Setter; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @@ -52,9 +50,9 @@ import org.onap.policy.rest.adapter.ClosedLoopFaultTriggerUISignatures; import org.onap.policy.rest.adapter.ClosedLoopSignatures; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.dao.CommonClassDao; -import org.onap.policy.rest.jpa.OnapName; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.VarbindDictionary; +import org.onap.policy.utils.PolicyUtils; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @@ -74,7 +72,6 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { private static final String CONNECT_TRAP_2 = "connectTrap2"; private static final String TRAP_COUNT_2 = "trapCount2"; private static final String TRIGGER_1 = "trigger1"; - private static final String ENC_UTF_8 = "UTF-8"; private static final String TRIGGER_2 = "trigger2"; protected PolicyRestAdapter policyAdapter = null; @@ -346,7 +343,8 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { } catch (NumberFormatException e) { try { trap1Attrib = getVarbindOid(trap1Attrib); - attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")"; + attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, + PolicyUtils.CHARACTER_ENCODING) + ")"; } catch (UnsupportedEncodingException e1) { policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e1); } @@ -354,7 +352,8 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { } else { try { trap1Attrib = getVarbindOid(trap1Attrib); - attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, ENC_UTF_8) + ")"; + attributesStr = attributesStr + "(" + URLEncoder.encode(trap1Attrib, + PolicyUtils.CHARACTER_ENCODING) + ")"; } catch (UnsupportedEncodingException e) { policyLogger.error("Caused Exception while Encoding Varbind Dictionary Values", e); } @@ -515,27 +514,8 @@ public class CreateClosedLoopFaultController extends RestrictedBaseController { .forEach(match -> { // Under the match we have attribute value and // attributeDesignator. So,finally down to the actual attribute. - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - OnapName onapName = new OnapName(); - onapName.setOnapName(value); - policyAdapter.setOnapNameField(onapName); - } else if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } else if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } else if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); })); } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java index 8d47be76c..058542590 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateClosedLoopPMController.java @@ -52,6 +52,12 @@ public class CreateClosedLoopPMController { protected PolicyRestAdapter policyAdapter = null; + /** + * prePopulateClosedLoopPMPolicyData. + * + * @param policyAdapter PolicyRestAdapter + * @param entity PolicyEntity + */ public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) { if (! (policyAdapter.getPolicyData() instanceof PolicyType)) { return; @@ -116,19 +122,8 @@ public class CreateClosedLoopPMController { AttributeDesignatorType designator = match.getAttributeDesignator(); String attributeId = designator.getAttributeId(); // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } else if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } else if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } else if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } else if ("ServiceType".equals(attributeId)) { + policyAdapter.setupUsingAttribute(attributeId, value); + if ("ServiceType".equals(attributeId)) { LinkedHashMap<String, String> serviceTypePolicyName1 = new LinkedHashMap<>(); serviceTypePolicyName1.put(KEY_SERVICE_TYPE_POLICY_NAME, value); policyAdapter.setServiceTypePolicyName(serviceTypePolicyName1); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java index 2549e2167..f0b3313a6 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateDcaeMicroServiceController.java @@ -72,8 +72,6 @@ import lombok.Getter; import lombok.Setter; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @@ -99,6 +97,7 @@ import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.util.MSAttributeObject; import org.onap.policy.rest.util.MSModelUtils; import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; +import org.onap.policy.utils.PolicyUtils; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.web.support.JsonMessage; import org.springframework.beans.factory.annotation.Autowired; @@ -960,9 +959,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); List<Object> list = new ArrayList<>(); String responseString = mapper.writeValueAsString(returnModel); @@ -1183,6 +1182,14 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { return keys; } + /** + * getModelServiceVersionData. + * + * @param request HttpServletRequest + * @param response HttpServletResponse + * @return ModelAndView + * @throws IOException IOException + */ @RequestMapping( value = {"/policyController/getModelServiceVersioneData.htm"}, method = {org.springframework.web.bind.annotation.RequestMethod.POST}) @@ -1191,9 +1198,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); List<Object> list = new ArrayList<>(); String value = mapper.readTree(request.getReader()).get("policyData").toString().replaceAll("^\"|\"$", ""); String servicename = value.split("-v")[0]; @@ -1311,29 +1318,9 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { // Under the match we have attribute value and // attributeDesignator. So,finally down to the actual attribute. // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } else if ("ConfigName".equals(attributeId)) { - policyAdapter.setConfigName(value); - } else if ("uuid".equals(attributeId)) { - policyAdapter.setUuid(value); - } else if ("location".equals(attributeId)) { - policyAdapter.setLocation(value); - } else if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } else if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } else if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } else if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - String newDate = new PolicyController().convertDate(value); - policyAdapter.setTtlDate(newDate); - } + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); } readFile(policyAdapter, entity); } @@ -1397,6 +1384,12 @@ public class CreateDcaeMicroServiceController extends RestrictedBaseController { } + /** + * readRecursivlyJSONContent. + * + * @param map Map of String to something + * @param data Map of String to Object + */ @SuppressWarnings({"rawtypes", "unchecked"}) public void readRecursivlyJSONContent(Map<String, ?> map, Map<String, Object> data) { for (Iterator iterator = map.keySet().iterator(); iterator.hasNext();) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java index 0fbc34d71..cb0263f2f 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateFirewallController.java @@ -39,8 +39,6 @@ import javax.servlet.http.HttpServletResponse; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @@ -75,6 +73,7 @@ import org.onap.policy.rest.jpa.PrefixList; import org.onap.policy.rest.jpa.SecurityZone; import org.onap.policy.rest.jpa.ServiceList; import org.onap.policy.rest.jpa.TermList; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.beans.factory.annotation.Autowired; @@ -278,27 +277,8 @@ public class CreateFirewallController extends RestrictedBaseController { // Under the match we have attribute value and // attributeDesignator. So,finally down to the actual attribute. // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - if (("ConfigName").equals(attributeId)) { - policyAdapter.setConfigName(value); - } - if (("RiskType").equals(attributeId)) { - policyAdapter.setRiskType(value); - } - if (("RiskLevel").equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } - if (("guard").equals(attributeId)) { - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); } } } @@ -457,9 +437,9 @@ public class CreateFirewallController extends RestrictedBaseController { } } } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); String responseString = mapper.writeValueAsString(displayString); response.getWriter().write(new JSONObject("{policyData: " + responseString + "}").toString()); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java index afe2ce193..eb3b3246a 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreateOptimizationController.java @@ -55,8 +55,6 @@ import lombok.Getter; import lombok.Setter; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.TargetType; @@ -80,6 +78,7 @@ import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.util.MSAttributeObject; import org.onap.policy.rest.util.MSModelUtils; import org.onap.policy.rest.util.MSModelUtils.MODEL_TYPE; +import org.onap.policy.utils.PolicyUtils; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @@ -121,9 +120,7 @@ public class CreateOptimizationController extends RestrictedBaseController { public static final String MANYFALSE = ":MANY-false"; public static final String MODEL = "model"; public static final String MANY = "MANY-"; - public static final String UTF8 = "UTF-8"; public static final String MODELNAME = "modelName"; - public static final String APPLICATIONJSON = "application / json"; @Autowired private CreateOptimizationController(CommonClassDao commonClassDao) { @@ -296,9 +293,9 @@ public class CreateOptimizationController extends RestrictedBaseController { jsonModel = finalJsonObject.toString(); } - response.setCharacterEncoding(UTF8); - response.setContentType(APPLICATIONJSON); - request.setCharacterEncoding(UTF8); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); List<Object> list = new ArrayList<>(); String responseString = mapper.writeValueAsString(returnModel); JSONObject json = null; @@ -485,9 +482,9 @@ public class CreateOptimizationController extends RestrictedBaseController { final String value = root.get("policyData").toString().replaceAll("^\"|\"$", ""); final String servicename = value.split("-v")[0]; - response.setCharacterEncoding(UTF8); - response.setContentType(APPLICATIONJSON); - request.setCharacterEncoding(UTF8); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); List<Object> list = new ArrayList<>(); list.add(new JSONObject("{optimizationModelVersionData: " + mapper.writeValueAsString(getVersionList(servicename)) + "}")); @@ -572,28 +569,8 @@ public class CreateOptimizationController extends RestrictedBaseController { // Under the match we have attribute value and // attributeDesignator. So,finally down to the actual attribute. // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); - // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } - if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } - if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } - if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } + policyAdapter.setupUsingAttribute(match.getAttributeDesignator().getAttributeId(), + (String) match.getAttributeValue().getContent().get(0)); } readFile(policyAdapter, entity); } @@ -683,9 +660,9 @@ public class CreateOptimizationController extends RestrictedBaseController { } if (!errorMsg.isEmpty()) { - response.setCharacterEncoding(UTF8); - response.setContentType(APPLICATIONJSON); - request.setCharacterEncoding(UTF8); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); response.getWriter().write(new JSONObject().put("errorMsg", errorMsg).toString()); return; } @@ -753,9 +730,9 @@ public class CreateOptimizationController extends RestrictedBaseController { } - response.setCharacterEncoding(UTF8); - response.setContentType(APPLICATIONJSON); - request.setCharacterEncoding(UTF8); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); ObjectMapper mapper = new ObjectMapper(); JSONObject json = new JSONObject(); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java index 711228574..a2cf20834 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/CreatePolicyController.java @@ -27,8 +27,6 @@ import java.util.Map; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeDesignatorType; -import oasis.names.tc.xacml._3_0.core.schema.wd_17.AttributeValueType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.MatchType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.PolicyType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.RuleType; @@ -99,31 +97,10 @@ public class CreatePolicyController extends RestrictedBaseController { // Under the match we have attribute value and // attributeDesignator. So,finally down to the actual attribute. // - AttributeValueType attributeValue = match.getAttributeValue(); - String value = (String) attributeValue.getContent().get(0); - AttributeDesignatorType designator = match.getAttributeDesignator(); - String attributeId = designator.getAttributeId(); + String value = (String) match.getAttributeValue().getContent().get(0); + String attributeId = match.getAttributeDesignator().getAttributeId(); // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } - if ("RiskType".equals(attributeId)) { - policyAdapter.setRiskType(value); - } - if ("RiskLevel".equals(attributeId)) { - policyAdapter.setRiskLevel(value); - } - if ("guard".equals(attributeId)) { - policyAdapter.setGuard(value); - } - if ("TTLDate".equals(attributeId) && !value.contains("NA")) { - PolicyController controller = new PolicyController(); - String newDate = controller.convertDate(value); - policyAdapter.setTtlDate(newDate); - } - if ("ConfigName".equals(attributeId)) { - policyAdapter.setConfigName(value); - } + policyAdapter.setupUsingAttribute(attributeId, value); // After Onap and Config it is optional to have attributes, so // check weather dynamic values or there or not. if (index >= 7) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java index 891398aef..dee92925a 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DashboardController.java @@ -188,7 +188,7 @@ public class DashboardController extends RestrictedBaseController { model.put("policyStatusCRUDData", mapper.writeValueAsString(policyStatusCrudData)); response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(model))).toString()); } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); PrintWriter out = response.getWriter(); out.write(PolicyUtils.CATCH_EXCEPTION); } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java index 8ecf3692d..c3b474521 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/DecisionPolicyController.java @@ -25,7 +25,6 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; @@ -170,9 +169,7 @@ public class DecisionPolicyController extends RestrictedBaseController { AttributeDesignatorType designator = match.getAttributeDesignator(); String attributeId = designator.getAttributeId(); // First match in the target is OnapName, so set that value. - if ("ONAPName".equals(attributeId)) { - policyAdapter.setOnapName(value); - } + policyAdapter.setupUsingAttribute(attributeId, value); // Component attributes are saved under Target here we are fetching them back. // One row is default so we are not adding dynamic component at index 0. if (index >= 1) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java index b50ca6d94..0c0c15f05 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/ExportAndImportDecisionBlackListEntries.java @@ -61,6 +61,7 @@ import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.rest.adapter.PolicyRestAdapter; import org.onap.policy.rest.adapter.ReturnBlackList; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.web.support.JsonMessage; @@ -146,9 +147,9 @@ public class ExportAndImportDecisionBlackListEntries extends RestrictedBaseContr workBook.write(fos); fos.flush(); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); PrintWriter out = response.getWriter(); String successMap = file.substring(file.lastIndexOf("webapps") + 8); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java index ae866c44a..f2f7d57af 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PDPController.java @@ -27,7 +27,6 @@ import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; -import java.io.PrintWriter; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; @@ -44,6 +43,7 @@ import org.onap.policy.admin.RESTfulPAPEngine; import org.onap.policy.common.logging.flexlogger.FlexLogger; import org.onap.policy.common.logging.flexlogger.Logger; import org.onap.policy.model.PDPGroupContainer; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.OnapPDPGroup; @@ -195,6 +195,11 @@ public class PDPController extends RestrictedBaseController { method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void savePDPGroup(HttpServletRequest request, HttpServletResponse response) { try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // ObjectMapper mapper = new ObjectMapper(); PolicyController controller = getPolicyControllerInstance(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -223,20 +228,14 @@ public class PDPController extends RestrictedBaseController { + message + e); } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setContentType(PolicyUtils.APPLICATION_JSON); refreshGroups(request); response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); } catch (Exception e) { policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e); - response.setCharacterEncoding("UTF-8"); - PrintWriter out = null; try { - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); + response.getWriter().write(e.getMessage()); } catch (Exception e1) { policyLogger .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Saving the PDP Group" + e1); @@ -255,6 +254,11 @@ public class PDPController extends RestrictedBaseController { method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void removePDPGroup(HttpServletRequest request, HttpServletResponse response) { try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); @@ -275,19 +279,13 @@ public class PDPController extends RestrictedBaseController { this.container.removeGroup(pdpGroupData, null); } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setContentType(PolicyUtils.APPLICATION_JSON); refreshGroups(request); response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); } catch (Exception e) { policyLogger.error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing the PDP Group" + e); - PrintWriter out; try { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); + response.getWriter().write(e.getMessage()); } catch (Exception e1) { policyLogger.error("Exception Occured" + e1); } @@ -305,6 +303,11 @@ public class PDPController extends RestrictedBaseController { method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void savePDPToGroup(HttpServletRequest request, HttpServletResponse response) { try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); @@ -336,20 +339,14 @@ public class PDPController extends RestrictedBaseController { + "Error Occured while Creating Pdp in PDP Group" + message + e); } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setContentType(PolicyUtils.APPLICATION_JSON); refreshGroups(request); response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); } catch (Exception e) { policyLogger .error(XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Creating Pdp in PDP Group" + e); - PrintWriter out; try { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - out = response.getWriter(); - out.write(e.getMessage()); + response.getWriter().write(e.getMessage()); } catch (Exception e1) { policyLogger.error("Exception Occured" + e1); } @@ -367,6 +364,11 @@ public class PDPController extends RestrictedBaseController { method = {org.springframework.web.bind.annotation.RequestMethod.POST}) public void removePDPFromGroup(HttpServletRequest request, HttpServletResponse response) { try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // ObjectMapper mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); JsonNode root = mapper.readTree(request.getReader()); @@ -384,9 +386,7 @@ public class PDPController extends RestrictedBaseController { StdPDP deletePdp = mapper.readValue(root.get("data").toString(), StdPDP.class); StdPDPGroup activeGroupData = mapper.readValue(root.get("activePDP").toString(), StdPDPGroup.class); this.container.removePDP(deletePdp, activeGroupData); - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setContentType(PolicyUtils.APPLICATION_JSON); refreshGroups(request); response.getWriter().write(new JSONObject(new JsonMessage(mapper.writeValueAsString(groups))).toString()); @@ -394,8 +394,6 @@ public class PDPController extends RestrictedBaseController { policyLogger.error( XACMLErrorConstants.ERROR_DATA_ISSUE + "Error Occured while Removing Pdp from PDP Group" + e); try { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); response.getWriter().write(e.getMessage()); } catch (Exception e1) { policyLogger.error("Exception Occured" + e1); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java index 7769ac7d0..5e957c40c 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyController.java @@ -64,6 +64,7 @@ import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.rest.jpa.UserInfo; import org.onap.policy.utils.PeCryptoUtils; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.policy.xacml.api.pap.PAPPolicyEngine; @@ -112,8 +113,6 @@ public class PolicyController extends RestrictedBaseController { // Constant variables used across Policy-sdk private static final String policyData = "policyData"; - private static final String characterEncoding = "UTF-8"; - private static final String contentType = "application/json"; private static final String file = "file"; private static final String SUPERADMIN = "super-admin"; private static final String POLICYGUEST = "Policy Guest"; @@ -945,11 +944,11 @@ public class PolicyController extends RestrictedBaseController { } public static String getCharacterencoding() { - return characterEncoding; + return PolicyUtils.CHARACTER_ENCODING; } public static String getContenttype() { - return contentType; + return PolicyUtils.APPLICATION_JSON; } public static String getFile() { @@ -974,17 +973,4 @@ public class PolicyController extends RestrictedBaseController { return fileSizeLimit; } - /** - * Function to convert date. - * - * @param dateTimeToLive input date value. - * @return - */ - public String convertDate(String dateTimeToLive) { - String formatDate = null; - if (dateTimeToLive.contains("-")) { - formatDate = dateTimeToLive.replace("-", "/"); - } - return formatDate; - } } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java index 380341ffa..8f508ca31 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyExportAndImportController.java @@ -64,6 +64,7 @@ import org.onap.policy.rest.jpa.PolicyEditorScopes; import org.onap.policy.rest.jpa.PolicyEntity; import org.onap.policy.rest.jpa.PolicyVersion; import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.utils.PolicyUtils; import org.onap.policy.utils.UserUtils.Pair; import org.onap.policy.xacml.api.XACMLErrorConstants; import org.onap.portalsdk.core.controller.RestrictedBaseController; @@ -174,8 +175,8 @@ public class PolicyExportAndImportController extends RestrictedBaseController { workBook2.write(fos); fos.flush(); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); PrintWriter out = response.getWriter(); String successMap = file.substring(file.lastIndexOf("webapps") + 8); diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java index 51bc3e987..ebd24dce3 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyNotificationController.java @@ -30,7 +30,6 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import java.io.File; import java.io.IOException; -import java.io.PrintWriter; import java.util.List; import javax.script.SimpleBindings; @@ -71,6 +70,11 @@ public class PolicyNotificationController extends RestrictedBaseController { StringBuilder path = new StringBuilder(); String responseValue = ""; try { + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + // + // + // String userId = UserUtils.getUserSession(request).getOrgUserId(); logger.info("userid info: " + userId); ObjectMapper mapper = new ObjectMapper(); @@ -118,18 +122,13 @@ public class PolicyNotificationController extends RestrictedBaseController { responseValue = "You have UnSubscribed Successfully"; } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setContentType(PolicyUtils.APPLICATION_JSON); response.getWriter().write(new JSONObject("{watchData: " + mapper.writeValueAsString(responseValue) + "}").toString()); } catch (Exception e) { - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); logger.error("Error druing watchPolicy function " + e); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + response.getWriter().write(PolicyUtils.CATCH_EXCEPTION); } return null; } diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java index 4fa848edd..c1c784083 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyRolesController.java @@ -42,6 +42,7 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.PolicyEditorScopes; import org.onap.policy.rest.jpa.PolicyRoles; import org.onap.policy.rest.jpa.UserInfo; +import org.onap.policy.utils.PolicyUtils; import org.onap.portalsdk.core.controller.RestrictedBaseController; import org.onap.portalsdk.core.web.support.JsonMessage; import org.onap.portalsdk.core.web.support.UserUtils; @@ -147,9 +148,9 @@ public class PolicyRolesController extends RestrictedBaseController { } else { commonClassDao.update(roles); } - response.setCharacterEncoding("UTF-8"); - response.setContentType("application / json"); - request.setCharacterEncoding("UTF-8"); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.setContentType(PolicyUtils.APPLICATION_JSON); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); response.getWriter().write(new JSONObject("{rolesDatas: " + mapper.writeValueAsString(commonClassDao.getUserRoles()) + "}").toString()); } catch (Exception e) { diff --git a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java index 0c29f8fb7..05264c8b6 100644 --- a/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java +++ b/POLICY-SDK-APP/src/main/java/org/onap/policy/controller/PolicyValidationController.java @@ -23,7 +23,6 @@ package org.onap.policy.controller; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; -import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @@ -73,10 +72,9 @@ public class PolicyValidationController extends RestrictedBaseController { new JsonMessage(mapper.writeValueAsString(responseString.toString()))).toString()); } catch (Exception e) { LOGGER.error("Exception Occured During Policy Validation" + e); - response.setCharacterEncoding("UTF-8"); - request.setCharacterEncoding("UTF-8"); - PrintWriter out = response.getWriter(); - out.write(PolicyUtils.CATCH_EXCEPTION); + response.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + request.setCharacterEncoding(PolicyUtils.CHARACTER_ENCODING); + response.getWriter().write(PolicyUtils.CATCH_EXCEPTION); } return null; } diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java index 0325c8d8f..244901a3f 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyManagerServletTest.java @@ -71,6 +71,11 @@ public class PolicyManagerServletTest extends Mockito { private HttpServletRequest request; private MockHttpServletResponse response; + /** + * setUp. + * + * @throws Exception should not get one + */ @Before public void setUp() throws Exception { logger.info("setUp: Entering"); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java index 4449676d3..5111ef2a8 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/admin/PolicyNotificationMailTest.java @@ -45,6 +45,11 @@ public class PolicyNotificationMailTest { private CommonClassDao commonClassDao; private List<Object> data = null; + /** + * setUp. + * + * @throws Exception should not throw one + */ @Before public void setUp() throws Exception { PolicyController.setjUnit(true); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java index 96320e7bc..1a99fdf92 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateDcaeMicroServiceControllerTest.java @@ -74,10 +74,9 @@ import org.springframework.mock.web.MockHttpServletResponse; /** * The class <code>CreateDcaeMicroServiceControllerTest</code> contains tests for the class - * {@link <code>CreateDcaeMicroServiceController</code>}* * - * All JUnits are designed to run in the local development environment where they have write privileges and can execute - * time-sensitive tasks. + * <p/>All JUnits are designed to run in the local development environment where they have write privileges + * and can execute time-sensitive tasks. * */ @@ -89,11 +88,15 @@ public class CreateDcaeMicroServiceControllerTest { private String configBodyString = null; private HttpServletRequest request = null; + /** + * setUp. + * + * @throws Exception should not throw one + */ @Before public void setUp() throws Exception { logger.info("setUp: Entering"); commonClassDao = mock(CommonClassDao.class); - List<Object> microServiceModelsData = new ArrayList<Object>(); MicroServiceModels testData = new MicroServiceModels(); testData.setVersion("OpenOnap-Junit"); testData.setModelName("modelName"); @@ -140,6 +143,7 @@ public class CreateDcaeMicroServiceControllerTest { testData.setDataOrderInfo("triggerSignature.signaturesAlarm.alarmSignatures.alarmSignature[VnfType, Contains, " + "FilterValue]@SymptomTriggerSignature.signaturesSymptom.symptomSignatures." + "symptomSignature[symptomVnfType, symptomContains, symptomFilterValue]"); + List<Object> microServiceModelsData = new ArrayList<Object>(); microServiceModelsData.add(testData); // mock the getDataById() call @@ -353,11 +357,8 @@ public class CreateDcaeMicroServiceControllerTest { try { root = JsonLoader.fromString(jsonString); restAdapter = mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); - TargetType target = new TargetType(); // create guard attribute - AnyOfType anyOfType = new AnyOfType(); - AllOfType alltype = new AllOfType(); MatchType matchType = new MatchType(); // set value AttributeValueType attributeValue1 = new AttributeValueType(); @@ -367,6 +368,7 @@ public class CreateDcaeMicroServiceControllerTest { AttributeDesignatorType designator = new AttributeDesignatorType(); designator.setAttributeId("guard"); matchType.setAttributeDesignator(designator); + AllOfType alltype = new AllOfType(); alltype.getMatch().add(matchType); // add a dummy MatchType object since while (matchList.size()>1 ...) @@ -381,8 +383,10 @@ public class CreateDcaeMicroServiceControllerTest { matchDummy.setAttributeDesignator(designatorDummy); alltype.getMatch().add(matchDummy); + AnyOfType anyOfType = new AnyOfType(); anyOfType.getAllOf().add(alltype); + TargetType target = new TargetType(); target.getAnyOf().add(anyOfType); // create RiskType attribute diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java index 6a5e83f4e..8e1b8be87 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreateOptimizationControllerTest.java @@ -66,14 +66,12 @@ import org.onap.policy.rest.dao.CommonClassDao; import org.onap.policy.rest.jpa.ConfigurationDataEntity; import org.onap.policy.rest.jpa.OptimizationModels; import org.onap.policy.rest.jpa.PolicyEntity; -import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; /** * The class <code>CreateOptimizationControllerTest</code> contains tests for the class - * {@link <code>CreateOptimizationController</code>}* * - * All JUnits are designed to run in the local development environment where they have write + * <p/>All JUnits are designed to run in the local development environment where they have write * privileges and can execute time-sensitive tasks. */ public class CreateOptimizationControllerTest { @@ -126,7 +124,7 @@ public class CreateOptimizationControllerTest { } /** - * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test + * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test. */ @Test @@ -143,7 +141,7 @@ public class CreateOptimizationControllerTest { PolicyRestAdapter policyData = null; try { root = JsonLoader.fromString(jsonString); - policyData = (PolicyRestAdapter) mapper.readValue(root.get("policyData").get("policy").toString(), + policyData = mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); } catch (Exception e) { logger.error("testSetDataToPolicyRestAdapter", e); @@ -158,7 +156,7 @@ public class CreateOptimizationControllerTest { /** * Run the ModelAndView getOptimizationTemplateData(HttpServletRequest, HttpServletResponse) - * method test + * method test. */ @Test @@ -201,7 +199,7 @@ public class CreateOptimizationControllerTest { /** * Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse) - * method test + * method test. */ @Test @@ -244,7 +242,7 @@ public class CreateOptimizationControllerTest { } /** - * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test + * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test. */ @Test @@ -267,7 +265,7 @@ public class CreateOptimizationControllerTest { try { root = JsonLoader.fromString(jsonString); - restAdapter = (PolicyRestAdapter) mapper.readValue(root.get("policyData").get("policy").toString(), + restAdapter = mapper.readValue(root.get("policyData").get("policy").toString(), PolicyRestAdapter.class); PolicyType policyType = new PolicyType(); TargetType target = new TargetType(); @@ -387,7 +385,7 @@ public class CreateOptimizationControllerTest { } /** - * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test + * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test. */ @Test @@ -429,9 +427,7 @@ public class CreateOptimizationControllerTest { } /** - * - * @ Get File Stream - * + * @ Get File Stream. */ private class MockServletInputStream extends ServletInputStream { diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java index 6a431a0af..79277d81d 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/CreatePolicyControllerTest.java @@ -20,9 +20,9 @@ package org.onap.policy.controller; -import static org.junit.Assert.*; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; + import com.att.research.xacml.api.XACML3; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AllOfType; import oasis.names.tc.xacml._3_0.core.schema.wd_17.AnyOfType; diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java index f86f3532c..413849cd3 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/DashboardControllerTest.java @@ -54,6 +54,11 @@ public class DashboardControllerTest { private Path repo; StdEngine engine = null; + /** + * setUp. + * + * @throws Exception should not get one + */ @Before public void setUp() throws Exception { logger.info("setUp: Entering"); diff --git a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java index af3c88257..554c40f90 100644 --- a/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java +++ b/POLICY-SDK-APP/src/test/java/org/onap/policy/controller/PolicyControllerTest.java @@ -47,12 +47,16 @@ public class PolicyControllerTest { private static Logger logger = FlexLogger.getLogger(PolicyControllerTest.class); private static CommonClassDao commonClassDao; + /** + * setUp. + * + * @throws Exception Should not throw one + */ @Before public void setUp() throws Exception { logger.info("setUp: Entering"); commonClassDao = mock(CommonClassDao.class); PolicyController.setCommonClassDao(commonClassDao); - List<Object> data = new ArrayList<>(); String policyData = ""; try { ClassLoader classLoader = getClass().getClassLoader(); @@ -64,6 +68,7 @@ public class PolicyControllerTest { entity.setPolicyName("Config_SampleTest.1.xml"); entity.setPolicyData(policyData); entity.setScope("com"); + List<Object> data = new ArrayList<>(); data.add(entity); when(commonClassDao.getDataByQuery( diff --git a/POLICY-SDK-APP/src/test/resources/xacml.admin.properties b/POLICY-SDK-APP/src/test/resources/xacml.admin.properties index 363ab621f..1147ce6eb 100644 --- a/POLICY-SDK-APP/src/test/resources/xacml.admin.properties +++ b/POLICY-SDK-APP/src/test/resources/xacml.admin.properties @@ -2,7 +2,7 @@ # ============LICENSE_START======================================================= # ONAP Policy Engine # ================================================================================ -# Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. +# Copyright (C) 2017, 2019 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. @@ -111,9 +111,9 @@ xacml.max.priority.count=10 # # You can test authorization within the Admin Console by changing the user id. # There are 3 supported user ids: -# guest - Read only access -# editor - Read/Write access -# admin - Read/Write/Admin access +# guest - Read only access +# editor - Read/Write access +# admin - Read/Write/Admin access # # An empty or null value for xacml.rest.admin.user.id results in no access to the application at all. # diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java index f8af9c4f2..1b55fef91 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/ManualClientEndUEBTest.java @@ -22,7 +22,6 @@ package org.onap.policy.std.test; -import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import java.util.LinkedList; import java.util.List; diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java index cb5c40c60..ce1794450 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/std/test/NotificationStoreTest.java @@ -25,7 +25,6 @@ package org.onap.policy.std.test; import org.junit.*; import org.onap.policy.std.NotificationStore; import org.onap.policy.std.StdPDPNotification; -import static org.junit.Assert.*; /** * The class <code>NotificationStoreTest</code> contains tests for the class diff --git a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java index e7d82499f..a5c4e85fa 100644 --- a/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java +++ b/PolicyEngineAPI/src/test/java/org/onap/policy/test/PolicyConfigStatusTest.java @@ -7,9 +7,9 @@ * 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. @@ -23,8 +23,6 @@ package org.onap.policy.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import org.junit.After; -import org.junit.Before; import org.junit.Test; import org.onap.policy.api.PolicyConfigStatus; diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java index ab87bc093..236f01eff 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/AAFPolicyClient.java @@ -33,6 +33,13 @@ public interface AAFPolicyClient { public boolean checkPerm(String userName, String pass, String type, String instance, String action); + /** + * getInstance. + * + * @param properties Properties + * @return AAFPolicyClient + * @throws AAFPolicyException AAFPolicyException + */ public static AAFPolicyClient getInstance(Properties properties) throws AAFPolicyException { try { Class<?> aafPolicyClient = Class diff --git a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java index 9c1294540..7d70da2f7 100644 --- a/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java +++ b/PolicyEngineUtils/src/main/java/org/onap/policy/utils/PolicyUtils.java @@ -53,11 +53,14 @@ import org.xml.sax.XMLReader; public class PolicyUtils { private static final Logger LOGGER = FlexLogger.getLogger(PolicyUtils.class); + private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package"; + public static final String CATCH_EXCEPTION = "PE500: An exception was caught."; public static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; - private static final String PACKAGE_ERROR = "mismatched input '{' expecting one of the following tokens: '[package"; public static final String SUCCESS = "success"; + public static final String CHARACTER_ENCODING = "UTF-8"; + public static final String APPLICATION_JSON = "application/json"; private PolicyUtils() { // Private Constructor diff --git a/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml b/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml index 6cd88bf28..93a2acf05 100644 --- a/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml +++ b/PolicyEngineUtils/src/main/resources/META-INF/persistencePU.xml @@ -3,14 +3,14 @@ ============LICENSE_START======================================================= PolicyEngineUtils ================================================================================ - Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + Copyright (C) 2017, 2019 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. @@ -20,10 +20,12 @@ --> <persistence version="2.1" - xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> - <persistence-unit name="PolicyEngineUtils" transaction-type="RESOURCE_LOCAL"> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> - <class>org.onap.policy.jpa.BackUpMonitorEntity</class> - </persistence-unit> + xmlns="http://xmlns.jcp.org/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> + <persistence-unit name="PolicyEngineUtils" + transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <class>org.onap.policy.jpa.BackUpMonitorEntity</class> + </persistence-unit> </persistence> diff --git a/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml b/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml index a73e6b3c5..17cdce68d 100644 --- a/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml +++ b/PolicyEngineUtils/src/test/resources/META-INF/persistencePUtest.xml @@ -1,35 +1,52 @@ <?xml version="1.0" encoding="UTF-8"?> -<!-- ============LICENSE_START======================================================= - PolicyEngineUtils ================================================================================ - 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========================================================= --> +<!-- + ============LICENSE_START======================================================= + PolicyEngineUtils + ================================================================================ + Copyright (C) 2017, 2019 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========================================================= + --> <persistence version="2.1" - xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> - <persistence-unit name="PolicyEngineUtils" - transaction-type="RESOURCE_LOCAL"> - <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> - <class>org.onap.policy.jpa.BackUpMonitorEntity</class> - <property name="javax.persistence.schema-generation.scripts.action" - value="drop-and-create" /> - <property name="javax.persistence.schema-generation.scripts.create-target" - value="./src/test/resources/META-INF/generatedCreate.ddl" /> - <property name="javax.persistence.schema-generation.scripts.drop-target" - value="./src/test/resources/META-INF/generatedDrop.ddl" /> - <property name="javax.persistence.schema-generation.database.action" - value="drop-and-create" /> - <property name="javax.persistence.schema-generation.create-source" - value="metadata-then-script" /> - <property name="javax.persistence.schema-generation.drop-source" - value="script" /> - <property name="javax.persistence.schema-generation.drop-script-source" - value="META-INF/drop.ddl" /> - </persistence-unit> + xmlns="http://xmlns.jcp.org/xml/ns/persistence" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> + <persistence-unit name="PolicyEngineUtils" + transaction-type="RESOURCE_LOCAL"> + <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> + <class>org.onap.policy.jpa.BackUpMonitorEntity</class> + <property + name="javax.persistence.schema-generation.scripts.action" + value="drop-and-create" /> + <property + name="javax.persistence.schema-generation.scripts.create-target" + value="./src/test/resources/META-INF/generatedCreate.ddl" /> + <property + name="javax.persistence.schema-generation.scripts.drop-target" + value="./src/test/resources/META-INF/generatedDrop.ddl" /> + <property + name="javax.persistence.schema-generation.database.action" + value="drop-and-create" /> + <property + name="javax.persistence.schema-generation.create-source" + value="metadata-then-script" /> + <property + name="javax.persistence.schema-generation.drop-source" + value="script" /> + <property + name="javax.persistence.schema-generation.drop-script-source" + value="META-INF/drop.ddl" /> + </persistence-unit> </persistence> |