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;
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;
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;
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;
// default constructor.
}
-
private static Properties readPipProperties() throws IOException {
if (pipProperties == null) {
try (FileInputStream inputStream = new FileInputStream(Paths.get("pip.properties").toString())) {
* ============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.
* ============LICENSE_END=========================================================
*/
-
package org.onap.policy.pap.xacml.rest;
/**
- *
+ *
* MessageCodes contains all the valid Dictionary names
*
*/
TermList,
SearchCriteria
}
-
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;
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;
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.
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;
@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;
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"));
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);
}
}
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;
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;
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;
}
}
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();
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();
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));
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");
}
}
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);
}
}
}
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;
private OnapLoggingContext loggingContext;
private List<Properties> properties;
-
public UpdatePdpThread(OnapPDP pdp, List<Properties> properties) {
this.pdp = pdp;
this.properties = properties;
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;
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;
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;
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;
* 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;
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
}
// 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()");
// 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
*/
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");
// 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);
}
}
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");
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) {
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 ";
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);
}
}
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);
// 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. ");
}
}
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) {
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");
}
}
}
@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 {
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");
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");
}
}
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();
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;
}
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;
}
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,
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;
}
@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);
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();
// 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) {
// 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;
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;
}
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");
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);
@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();
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();
}
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);
// 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) {
}
// 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();
@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();
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();
// 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) {
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
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;
// 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;
}
* @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 {
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.");
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);
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);
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);
}
}
- 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();
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();
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.";
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();
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();
}
}
- 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 + "')");
}
}
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");
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);
}
}
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.adapters;
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
+}
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.adapters;
public class UpdateObjectData {
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;
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;
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;
List<String> dynamicFieldOneRuleAlgorithms = new LinkedList<>();
List<String> dynamicFieldTwoRuleAlgorithms = new LinkedList<>();
-
private CommonClassDao commonClassDao;
private static boolean isAttribute = false;
return obligations;
}
-
// if compound setting the inner apply here
protected ApplyType getInnerActionApply(String value1Label) {
ApplyType actionApply = new ApplyType();
* ============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.
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;
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;
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);
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")) {
}
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);
}
}
- //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));
}
- //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")) {
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;
}
// 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);
advice.getAttributeAssignmentExpression().add(assignment5);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment6 = new AttributeAssignmentExpressionType();
assignment6.setAttributeId("RiskType");
assignment6.setCategory(CATEGORY_RESOURCE);
advice.getAttributeAssignmentExpression().add(assignment9);
-
advices.getAdviceExpression().add(advice);
return advices;
}
return policyAdapter.getPolicyData();
}
-
}
* ============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.
* ================================================================================
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;
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;
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 {
/**
}
}
-
// Here we are adding the extension for the configurations file based on the
// config type selection for saving.
private String getConfigFile(String filename) {
if (id == null) {
return filename;
}
- switch (id.toUpperCase())
- {
+ switch (id.toUpperCase()) {
case JSON_CONFIG:
return filename + ".json";
case XML_CONFIG:
return filename;
}
-
// Validations for Config form
/*
* FORM VALIDATION WILL BE DONE BY THE PAP-ADMIN before creating JSON object...
}
if (!isPreparedToSave()) {
- //Prep and configure the policy for saving
+ // Prep and configure the policy for saving
prepareToSave();
}
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 {
}
}
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("RiskType");
assignment8.setCategory(CATEGORY_RESOURCE);
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
import java.util.HashMap;
@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);
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");
}
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;
}
}
* ============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.
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;
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;
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);
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("$", "\\$");
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));
}
}
-
// Here we are adding the extension for the configurations file based on the
// config type selection for saving.
private String getConfigFile(String filename) {
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];
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++) {
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);
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();
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());
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
}
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);
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");
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.
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
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
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
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);
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<>();
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);
* ============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.
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.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;
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 {
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);
}
allOfOne.getMatch().add(createMatch("PolicyName", name));
-
AllOfType allOf = new AllOfType();
// Match for ONAPName
}
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);
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);
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();
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.
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
}
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
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
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);
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<>();
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();
.add(createResponseAttributes("key:" + keyField, entry.getValue()));
}
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("RiskType");
assignment8.setCategory(CATEGORY_RESOURCE);
* ============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.
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;
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;
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;
}
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();
}
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;
}
policyName = policyName + ".xml";
}
-
PolicyType configPolicy = (PolicyType) policyAdapter.getData();
configPolicy.setDescription(policyAdapter.getPolicyDescription());
// 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()));
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);
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);
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));
advice.getAttributeAssignmentExpression().add(assignment6);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment7 = new AttributeAssignmentExpressionType();
assignment7.setAttributeId("RiskType");
assignment7.setCategory(CATEGORY_RESOURCE);
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;
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;
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) {
try {
-
utils.parseTosca(fileName);
MSAttributeObject msAttributes = new MSAttributeObject();
}
mainClass = classMap.get(this.newModel.getModelName());
-
if (".yml".equalsIgnoreCase(type)) {
newModel.setDependency("[]");
* ============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.
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;
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);
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);
}
}
} 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);
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) {
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();
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);
}
}
- if (currentEntry.endsWith(".zip")){
+ if (currentEntry.endsWith(".zip")) {
extractFolder(destFile.getAbsolutePath());
}
}
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("}", ""));
}
}
- 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);
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");
}
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;
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;
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 {
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<>();
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@#";
}
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@");
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
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);
dataTypeList.add(dataType);
}
-
private String getDataType(String key) {
DecisionSettings decisionSettings = findDecisionSettingsBySettingId(key);
private AttributeDesignatorType generateAttributeDesignatorDataType(String functionKey) {
AttributeDesignatorType attributeDesignator = new AttributeDesignatorType();
- switch(functionKey.toLowerCase())
- {
+ switch (functionKey.toLowerCase()) {
case "integer":
attributeDesignator.setDataType(INTEGER_DATATYPE);
break;
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;
private AttributeValueType generateAttributeValueTypeDataType(String functionKey) {
AttributeValueType applyType = new AttributeValueType();
- switch(functionKey.toLowerCase())
- {
+ switch (functionKey.toLowerCase()) {
case "integer":
applyType.setDataType(INTEGER_DATATYPE);
break;
}
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) {
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;
}
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;
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;
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 {
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);
@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();
}
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());
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, "");
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;
}
}
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";
}
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);
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);
// 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");
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);
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);
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);
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);
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);
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);
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");
* 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) {
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) {
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();
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();
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();
destPortListString = getLeftOrRight(destPortListString, value);
}
- String destPortListInsert = "'"+destPortListString+"'";
+ String destPortListInsert = "'" + destPortListString + "'";
/*
* Create Queries to INSERT data into database tables and execute
* 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();
/*
* 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);
* 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();
}
prefixIP = getName(prefixIP, membersObj, type);
}
- String prefixList = "'"+prefixIP+"'";
+ String prefixList = "'" + prefixIP + "'";
Boolean isAddressGroup = type.contains("REFERENCE");
}
}
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;
+ "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);
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();
return name;
}
-
private Boolean updateFirewallDictionaryData(String jsonBody, String prevJsonBody) {
CommonClassDaoImpl dbConnection = new CommonClassDaoImpl();
JsonObject oldJson = null;
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;
}
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);
/*
* 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("\"", "");
}
}
- 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("\"", "");
}
}
- 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();
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();
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();
destPortListString = getLeftOrRight(destPortListString, value);
}
- String destPortListInsert = "'"+destPortListString+"'";
+ String destPortListInsert = "'" + destPortListString + "'";
/*
* Create Queries to INSERT data into database tables and execute
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);
}
}
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);
}
}
/*
* 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("\"", "");
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);
}
}
}
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;
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);
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);
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);
}
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();
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);
}
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;
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;
public static final String OTHER_CONFIG = "OTHER";
public static final String AUDIT_USER = "audit";
-
private static SessionFactory sessionfactory;
@Autowired
* ============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.
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;
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;
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 {
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;
}
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();
}
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;
}
policyName = policyName + ".xml";
}
-
PolicyType configPolicy = (PolicyType) policyAdapter.getData();
configPolicy.setDescription(policyAdapter.getPolicyDescription());
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));
// 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
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);
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);
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);
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();
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));
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);
advice.getAttributeAssignmentExpression().add(assignment6);
-
AttributeAssignmentExpressionType assignment8 = new AttributeAssignmentExpressionType();
assignment8.setAttributeId("matching:uuid");
assignment8.setCategory(CATEGORY_RESOURCE);
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);
advice.getAttributeAssignmentExpression().add(assignment10);
- //Risk Attributes
+ // Risk Attributes
AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
assignment11.setAttributeId("RiskType");
assignment11.setCategory(CATEGORY_RESOURCE);
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;
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;
* ============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.
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;
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;
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 {
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;
}
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();
}
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;
}
policyName = policyName + ".xml";
}
-
PolicyType configPolicy = (PolicyType) policyAdapter.getData();
configPolicy.setDescription(policyAdapter.getPolicyDescription());
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));
// 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);
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);
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);
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();
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);
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);
advice.getAttributeAssignmentExpression().add(assignment4);
- //OnapName Attribute Assignment
+ // OnapName Attribute Assignment
AttributeAssignmentExpressionType assignment5 = new AttributeAssignmentExpressionType();
assignment5.setAttributeId("matching:" + ONAPID);
assignment5.setCategory(CATEGORY_RESOURCE);
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");
advice.getAttributeAssignmentExpression().add(assignment10);
- //RiskType Attribute Assignment
+ // RiskType Attribute Assignment
AttributeAssignmentExpressionType assignment11 = new AttributeAssignmentExpressionType();
assignment11.setAttributeId("RiskType");
assignment11.setCategory(CATEGORY_RESOURCE);
advice.getAttributeAssignmentExpression().add(assignment11);
- //RiskLevel Attribute Assignment
+ // RiskLevel Attribute Assignment
AttributeAssignmentExpressionType assignment12 = new AttributeAssignmentExpressionType();
assignment12.setAttributeId("RiskLevel");
assignment12.setCategory(CATEGORY_RESOURCE);
advice.getAttributeAssignmentExpression().add(assignment12);
- //Guard Attribute Assignment
+ // Guard Attribute Assignment
AttributeAssignmentExpressionType assignment13 = new AttributeAssignmentExpressionType();
assignment13.setAttributeId("guard");
assignment13.setCategory(CATEGORY_RESOURCE);
advice.getAttributeAssignmentExpression().add(assignment13);
- //TTLDate Attribute Assignment
+ // TTLDate Attribute Assignment
AttributeAssignmentExpressionType assignment14 = new AttributeAssignmentExpressionType();
assignment14.setAttributeId("TTLDate");
assignment14.setCategory(CATEGORY_RESOURCE);
* ============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");
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;
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;
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 {
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;
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;
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";
private List<?> otherServers;
private PAPPolicyEngine papEngine;
-
/**
* Gets the current instance of 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();
// 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");
}
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;
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);
}
* @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;
}
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;
}
}
}
}
- 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]));
* 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<>();
// 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());
}
}
}
}
- 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];
}
* @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 {
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);
}
}
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);
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();
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;
} 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);
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]);
}
} 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;
}
// 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;
return papEngine;
}
-
public static boolean isJunit() {
return isJunit;
}
return scope + "." + PolicyDBDao.this.getConfigFile(filename, policy);
}
- String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName)
- throws PolicyDBException {
+ String[] getPolicyNameAndVersionFromPolicyFileName(String originalPolicyName) throws PolicyDBException {
return PolicyDBDao.this.getPolicyNameAndVersionFromPolicyFileName(originalPolicyName);
}
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;
*/
public void close();
-
/**
* Create a new PDP group in the database
*
public StdPDPGroup addPolicyToGroup(String group, String policyID, String requestType, String username)
throws PolicyDBException;
-
/**
* Delete an existing PDP groupPolicyDBException
*
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;
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;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
-
@Component
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;
private static SessionFactory sessionfactory;
-
/**
* Instantiates a new policy DB dao transaction instance.
*
}
}
-
public PolicyEntity getPolicy(int policyId) {
return getPolicy(policyId, null, null);
}
return configDataString;
}
-
@Override
public void close() {
synchronized (emLock) {
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.components;
import java.util.List;
public class SafePolicyBuilder {
- private SafePolicyBuilder(){
- //Private Constructor.
+ private SafePolicyBuilder() {
+ // Private Constructor.
}
public static ControlLoopGuard loadYamlGuard(String specification) {
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;
* ============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.
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 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 {
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);
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() {
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;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
-
@Controller
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();
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);
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)))
} else {
commonClassDao.update(bRMSParamTemplateData);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSParamTemplate.class));
} else {
responseString = duplicateResponseString;
}
}
@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");
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;
brmsDependency.setModifiedDate(new Date());
commonClassDao.update(brmsDependency);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(BRMSDependency.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(BRMSDependency.class));
} else {
responseString = duplicateResponseString;
}
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");
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;
brmsController.setModifiedDate(new Date());
commonClassDao.update(brmsController);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(OnapName.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(OnapName.class));
} else {
responseString = duplicateResponseString;
}
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);
}
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;
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();
}
@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);
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;
}
}
vSCLAction.setModifiedDate(new Date());
commonClassDao.update(vSCLAction);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(VSCLAction.class));
} else {
responseString = duplicateResponseString;
}
}
@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);
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;
}
}
}
@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);
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);
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;
}
}
pEPOptions.setModifiedDate(new Date());
commonClassDao.update(pEPOptions);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PEPOptions.class));
} else {
responseString = duplicateResponseString;
}
}
@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);
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;
}
}
serviceData.setModifiedDate(new Date());
commonClassDao.update(serviceData);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopD2Services.class));
} else {
responseString = duplicateResponseString;
}
}
@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);
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;
}
}
siteData.setModifiedDate(new Date());
commonClassDao.update(siteData);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ClosedLoopSite.class));
} else {
responseString = duplicateResponseString;
}
}
@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);
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;
}
}
varbindDictionary.setModifiedDate(new Date());
commonClassDao.update(varbindDictionary);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(VarbindDictionary.class));
} else {
responseString = duplicateResponseString;
}
}
@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);
}
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;
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();
}
@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);
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;
}
}
decisionSettings.setModifiedDate(new Date());
commonClassDao.update(decisionSettings);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(DecisionSettings.class));
} else {
responseString = duplicateResponseString;
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(decisionRainyDay);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(RainyDayTreatments.class));
} else {
responseString = duplicateResponseString;
}
}
@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);
}
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;
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);
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;
}
}
descriptiveScope.setModifiedDate(new Date());
commonClassDao.update(descriptiveScope);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(DescriptiveScope.class));
} else {
responseString = "Duplicate";
}
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);
}
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;
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();
}
// 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();
}
@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);
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) {
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");
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();
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;
}
}
}
@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);
}
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;
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);
}
@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");
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])
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;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
-
@Controller
public class FirewallDictionaryController {
private static String fwTagPickerDatas = "fwTagPickerDictionaryDatas";
private static String fwTagDatas = "fwTagDictionaryDatas";
-
@Autowired
public FirewallDictionaryController(CommonClassDao commonClassDao) {
FirewallDictionaryController.commonClassDao = commonClassDao;
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();
}
@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);
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;
}
}
} else {
commonClassDao.update(prefixList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(PrefixList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PrefixList.class));
} else {
responseString = duplicateResponseString;
}
}
@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());
}
}
- @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();
}
@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);
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;
}
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(protocolList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ProtocolList.class));
} else {
responseString = duplicateResponseString;
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(addressGroup);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(AddressGroup.class));
} else {
responseString = duplicateResponseString;
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(actionList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(ActionList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ActionList.class));
} else {
responseString = duplicateResponseString;
}
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();
}
@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);
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;
}
}
} else {
commonClassDao.update(groupServiceList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(GroupServiceList.class));
} else {
responseString = duplicateResponseString;
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(securityZone);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(SecurityZone.class));
} else {
responseString = duplicateResponseString;
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(serviceList);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(ServiceList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(ServiceList.class));
} else {
responseString = duplicateResponseString;
}
}
@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();
} 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;
}
}
}
@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();
}
@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);
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;
}
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(fwDictList);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(FirewallDictionaryList.class));
} else {
responseString = duplicateResponseString;
}
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();
}
@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);
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;
}
}
fwTagPicker.setModifiedDate(new Date());
commonClassDao.update(fwTagPicker);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(FWTagPicker.class));
} else {
responseString = duplicateResponseString;
}
}
@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);
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;
}
}
}
@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);
}
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;
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;
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();
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();
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();
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();
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) {
}
}
- @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 {
}
}
- @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 {
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 {
* ============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.
* 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;
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";
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;
}
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();
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());
}
}
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);
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);
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("}", ""));
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());
}
}
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;
@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";
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);
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)) {
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;
}
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;
}
}
} else {
commonClassDao.update(gpdata);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(GroupPolicyScopeList.class));
} else if (duplicateGroupFlag) {
responseString = "DuplicateGroup";
} else {
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();
}
@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);
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;
}
}
} else {
commonClassDao.update(onapData);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeClosedLoop.class));
} else {
responseString = duplicateResponseString;
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(onapData);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeService.class));
} else {
responseString = duplicateResponseString;
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(onapData);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeType.class));
} else {
responseString = duplicateResponseString;
}
}
@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();
}
@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);
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;
}
}
} else {
commonClassDao.update(onapData);
}
- responseString = mapper
- .writeValueAsString(commonClassDao.getData(PolicyScopeResource.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(PolicyScopeResource.class));
} else {
responseString = duplicateResponseString;
}
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;
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;
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) {
}
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) {
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");
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;
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();
}
@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);
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;
}
}
}
@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);
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;
}
}
} else {
commonClassDao.update(safePolicyWarning);
}
- responseString =
- mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class));
+ responseString = mapper.writeValueAsString(commonClassDao.getData(SafePolicyWarning.class));
} else {
responseString = duplicateResponseString;
}
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);
}
* ============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.
* ============LICENSE_END=========================================================
*/
-
package org.onap.policy.pap.xacml.rest.controller;
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;
private static final Log LOGGER = LogFactory.getLog(CommonClassDaoImpl.class);
-
private static SessionFactory sessionFactory;
-
@Autowired
private CommonClassDaoImpl(SessionFactory sessionFactory) {
CommonClassDaoImpl.sessionFactory = sessionFactory;
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) {
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;
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;
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);
}
}
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();
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) {
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) {
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();
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) {
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() {
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) {
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) {
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() {
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();
}
@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;
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;
}
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;
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;
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;
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)
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);
}
}
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) {
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 + "\",");
}
}
}
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);
}
- }
+ }
+ }
}
}
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 {
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;
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");
} 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);
}
}
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;
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();
}
}
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()) {
}
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;
}
}
}
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;
}
}
}
@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);
}
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()) {
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();
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();
}
return result;
}
-
@Override
public JestResult search(PolicyIndexType type, String text, Map<String, String> filter_s)
throws IllegalStateException, IllegalArgumentException {
}
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;
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(",")) {
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();
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();
}
}
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());
}
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();
* ============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.
* 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
+}
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk.client;
import java.util.ArrayList;
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;
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;
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();
}
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();
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();
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();
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;
}
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;
}
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;
}
* ============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.
* 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;
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>() {
}
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);
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;
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);
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";
}
}
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;
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();
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
+}
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk.client;
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;
}
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 + "|" + "]";
}
}
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;
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;
* ============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.
* 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();
/*
* 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;
}
* Get Equivalent for Dictionary Services.
*/
public void doDictionaryAPIGet(HttpServletRequest request, HttpServletResponse response);
+
/*
* Put Equivalent for Dictionary Services.
*/
*
* 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);
}
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;
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")) {
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;
}
}
- 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;
}
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;
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);
}
// 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);
// 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());
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;
}
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;
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.model;
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;
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;
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;
}
@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<>();
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);
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)) {
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");
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");
policyVersionDao.setHigherVersion(version);
policyVersionDao.setModifiedBy(modifiedBy);
policyVersionDao.setModifiedDate(new Date());
- }else{
+ } else {
body = "policyExists";
status = HttpStatus.CONFLICT;
response.setStatus(HttpServletResponse.SC_CONFLICT);
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");
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);
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);
}
}
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);
}
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();
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());
}
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<>();
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);
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);
}
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;
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);
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;
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);
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;
}
}
* ============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.
* 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;
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;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;
-
// TODO: Auto-generated Javadoc
/**
* The Class DictionaryService.
return result.getViewName();
}
-
-
/**
* Save micro service location dictionary.
*
return result.getViewName();
}
-
/**
* Gets the onap dictionary.
*
dictionary.getTermListDictionaryEntityData(response);
}
-
/**
* Gets the micro service location dictionary.
*
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;
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();
}
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);
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);
}
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);
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();
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;
* ============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.
* 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 {
}
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);
+ * }
+ * }
+ */
}
-
}
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;
}
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) {
}
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) {
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);
}
@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());
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) {
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;
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.
* ============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.
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;
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;
}
-
}
-
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;
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;
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;
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
}
}
- @SuppressWarnings({ "rawtypes", "unchecked" })
+ @SuppressWarnings({"rawtypes", "unchecked"})
private static void readProps() throws PAPException {
InputStream in;
pdpProp = new Properties();
}
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;
}
}
* ============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.
@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;
logger.info("Request URI: " + url);
- //getting authentication credentials
+ // getting authentication credentials
authCredentials = httpServletRequest.getHeader(AUTHENTICATION_HEADER);
// Check Authentication credentials
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 {
}
}
- //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
}
}
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");
@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);
logger.debug("cleanDb: exit");
}
-
/*
* Tests that a comparison between hashsets is successful if
* the entries match
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");
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;
}
}
// Two entries with the same field values
-
entry1.setFlag("flag1");
entry1.setResourceNodeName("node1");
entry1.setResourceName("resourceName");
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
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");
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
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");
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
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");
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
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
+}
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.test;
import static org.junit.Assert.assertTrue;
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");
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");
@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);
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);
}
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;
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;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
-
public class XACMLPAPTest {
private static final Log logger = LogFactory.getLog(XACMLPAPTest.class);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
-
@Test
public void testDecisonBLGuardPolicy() throws IOException, ServletException, SQLException {
httpServletRequest = Mockito.mock(HttpServletRequest.class);
Mockito.verify(httpServletResponse).addHeader("operation", "create");
}
-
private void setPolicyCreation() {
CommonClassDao commonClassDao = Mockito.mock(CommonClassDao.class);
PolicyCreation.setCommonClassDao(commonClassDao);
// 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"
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;
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;
pap.init(servletConfig);
}
-
/**
* Sets the up.
*
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);
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);
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);
consoleAndApi.doAcDelete(httpServletRequest, httpServletResponse, TESTGRP4, logContext, stdEngine);
assertTrue(HttpServletResponse.SC_NO_CONTENT == httpServletResponse.getStatus());
-
}
@Test
* ============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.
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;
@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";
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);
* ============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.
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);
* ============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.
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+
import org.junit.Test;
import org.onap.policy.pap.xacml.rest.XACMLPapServlet;
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);
// Restore the original system property
if (oldProperty != null) {
- System.setProperty(systemKey, oldProperty);
- }
- else {
+ System.setProperty(systemKey, oldProperty);
+ } else {
System.clearProperty(systemKey);
}
}
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.adapters;
import static org.junit.Assert.*;
public class SearchDataTest {
-
@Test
- public void testSearchData(){
+ public void testSearchData() {
String data = "Test";
SearchData searchData = new SearchData();
searchData.setQuery(data);
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.adapters;
import static org.junit.Assert.assertTrue;
public class UpdateObjectDataTest {
@Test
- public void testClosedLoopFaultTrapDatas(){
+ public void testClosedLoopFaultTrapDatas() {
UpdateObjectData updateObject = new UpdateObjectData();
updateObject.setAction("Rename");
assertTrue("Rename".equals(updateObject.getAction()));
* ============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
* ================================================================================
* 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;
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 {
@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");
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");
logger.info("setUp: exit");
}
- /**
- * @throws java.lang.Exception
- */
- @After
- public void tearDown() throws Exception {}
-
/**
* Test method for
* {@link org.openecomp.policy.pap.xacml.rest.components.ActionPolicy#savePolicies()}.
* ============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
* ================================================================================
* 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;
* ============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.
* 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();
policy.prepareToSave();
assertEquals(policy.isPreparedToSave(), true);
}
-}
\ No newline at end of file
+}
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;
@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");
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");
e.printStackTrace();
}
- assertEquals(successMap.get("success"),"success");
+ assertEquals(successMap.get("success"), "success");
}
/**
try {
response = component.prepareToSave();
} catch (Exception e) {
- logger.error("Exception Occured"+e);
+ logger.error("Exception Occured" + e);
}
assertTrue(response);
}
* ============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.
* 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;
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);
@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");
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");
when(mockFWConfig.savePolicies()).thenReturn(successMap);
successMap = mockFWConfig.savePolicies();
} catch (Exception e) {
- logger.error("Exception Occured"+e);
+ logger.error("Exception Occured" + e);
}
}
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
+}
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;
* ============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.
* 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;
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 {
// 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();
}
* ============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.
* 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.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;
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 {
// 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();
}
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;
import java.util.Properties;
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;
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, "");
session2.getTransaction().commit();
session2.close();
-
// add a pdp to a group
group = dbd.getNewTransaction();
try {
session3.getTransaction().commit();
session3.close();
-
group = dbd.getNewTransaction();
try {
group.removePdpFromGroup("http://localhost:4344/pdp/", "testuser");
session5.getTransaction().commit();
session5.close();
-
group = dbd.getNewTransaction();
try {
OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup1"), Paths.get("/"));
session7.getTransaction().commit();
session7.close();
-
group = dbd.getNewTransaction();
try {
OnapPDPGroup groupToDelete = new StdPDPGroup(PolicyDBDao.createNewPDPGroupId("testgroup2"), Paths.get("/"));
}
Assert.assertFalse(t.isTransactionOpen());
-
if (logger.isDebugEnabled()) {
Date date = new java.util.Date();
logger.debug("\n\nPolicyDBDaoTest.threadingStabilityTest() " + "\n a = dbd.getNewTransaction() "
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
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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();
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");
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);
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);
}
@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);
}
}
}
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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);
}
@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);
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);
@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");
}
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);
}
}
@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);
}
@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);
@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");
@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);
}
}
@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);
}
@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);
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);
}
@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);
logger.info("testRemoveBRMSControllerDictionary: exit");
}
}
-
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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 {
controller.setCommonClassDao(commonClassDao);
request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+ response = new MockHttpServletResponse();
new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
}
@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);
}
}
}
* ============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
* ================================================================================
* 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;
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;
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));
logger.info("setUp: exit");
}
- @After
- public void tearDown() throws Exception {}
-
@Test
public void testGetSettingsDictionaryByNameEntityData() {
logger.info("testGetSettingsDictionaryByNameEntityData: Entering");
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);
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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 {
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);
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
+}
* ============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.
* ============LICENSE_END=========================================================
*/
-
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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());
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);
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);
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);
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);
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);
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);
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);
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);
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);
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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);
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");
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");
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
@Test
public void testGetProtocolListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(ProtocolList.class, "protocolListDictionaryDatas", "protocolName",
+ test_WithGetDataByColumn(ProtocolList.class,
+ "protocolListDictionaryDatas", "protocolName",
() -> controller.getProtocolListDictionaryEntityDataByName(response));
}
@Test
public void testGetZoneDictionaryEntityData() {
- test_WithGetData(Zone.class, "zoneDictionaryDatas", () -> controller.getZoneDictionaryEntityData(response));
+ test_WithGetData(Zone.class, "zoneDictionaryDatas", () ->
+ controller.getZoneDictionaryEntityData(response));
}
@Test
@Test
public void testGetFWDictListDictionaryEntityDataByName() {
- test_WithGetDataByColumn(FirewallDictionaryList.class, "fwDictListDictionaryDatas", "parentItemName",
+ test_WithGetDataByColumn(FirewallDictionaryList.class,
+ "fwDictListDictionaryDatas", "parentItemName",
() -> controller.getFWDictListDictionaryEntityDataByName(response));
}
@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));
}
@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));
}
@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));
}
@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));
}
@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));
}
@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));
}
@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));
}
@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));
}
@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));
}
@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));
}
@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));
}
@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));
}
@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));
}
* ============LICENSE_END=========================================================
*/
-
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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;
logger.info("testSaveMicroServiceHeaderDefaultValues: exit");
}
-
@Test
public void testGetMicroServiceHeaderDefaultsEntityDataByName() {
logger.info("testGetMicroServiceHeaderDefaultsEntityDataByName: Entering");
logger.info("testRemoveMicroServiceHeaderDefaults: exit");
}
-
@Test
public void testGetDCAEUUIDDictionaryByNameEntityData() {
* ============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
* ================================================================================
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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 javax.servlet.http.HttpServletRequest;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.onap.policy.rest.jpa.UserInfo;
import org.springframework.mock.web.MockHttpServletResponse;
-
public class OptimizationDictionaryControllerTest {
private static Logger logger = FlexLogger.getLogger(OptimizationDictionaryControllerTest.class);
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();
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
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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 {
controller.setCommonClassDao(commonClassDao);
request = Mockito.mock(HttpServletRequest.class);
- response = new MockHttpServletResponse();
+ response = new MockHttpServletResponse();
new DictionaryUtils(commonClassDao);
DictionaryUtils.setDictionaryUtils(new DictionaryUtils());
mock(DictionaryUtils.class);
}
@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);
}
}
}
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;
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;
import org.onap.policy.rest.jpa.PolicyVersion;
import org.springframework.mock.web.MockServletConfig;
-
public class PushPolicyControllerTest {
private static Logger logger = FlexLogger.getLogger(PushPolicyControllerTest.class);
@BeforeClass
public static void beforeClassSetup() throws ServletException {
- sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("pushcontrollertest");
+ sessionFactory = PolicyDBDaoTest.setupH2DbDaoImpl("pushcontrollertest");
}
@Before
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();
}
@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);
}
}
return servletInputStream;
}
- @After
- public void destroy(){
- if(pap!=null)
- pap.destroy();
- }
+ @After
+ public void destroy() {
+ if (pap != null)
+ pap.destroy();
+ }
}
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.controller;
import static org.junit.Assert.assertTrue;
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 {
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);
}
}
}
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk;
import static org.junit.Assert.assertTrue;
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");
configurationEntity.setDescription("test");
configurationEntity.setModifiedBy("Test");
configurationEntity.setModifiedDate(new Date());
-
-
+
PolicyEntity entity = new PolicyEntity();
entity.setPolicyName("Config_SampleTest.1.xml");
entity.setPolicyData(policyContent.toString());
}
@After
- public void reset(){
+ public void reset() {
System.clearProperty("PROPERTY_FILE");
}
}
* ============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.
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;
}
@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();
}
}
fail("Expected exception to be thrown");
}
-
@Test
public void testPut() throws IOException {
thrown.expect(NullPointerException.class);
* ============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.
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;
* ============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.
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;
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);
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);
* ============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.
* limitations under the License.
* ============LICENSE_END=========================================================
*/
+
package org.onap.policy.pap.xacml.rest.elk;
import static org.junit.Assert.assertEquals;
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\"}}");
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) {
* ============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.
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;
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);
}
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;
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);
+ }
}
* ============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
* ================================================================================
package org.onap.policy.pap.xacml.rest.handler;
import static org.junit.Assert.assertNull;
+
import org.junit.Test;
public class DictionaryHandlerTest {
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;
import org.onap.policy.xacml.std.pap.StdPDPGroup;
import org.onap.policy.xacml.std.pap.StdPDPPolicy;
-
public class PushPolicyHandlerTest {
@Test
public void testGetsAndChecks() {
* ============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.
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;
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, "");
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);
}
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();
}
-
+
}
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;
* ============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.
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
* ============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.
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;
MockHttpServletResponse response = new MockHttpServletResponse();
MetricService.doGetPolicyMetrics(response);
- assertEquals(response.getStatusCode(), HttpServletResponse.SC_BAD_REQUEST);
+ assertEquals(HttpServletResponse.SC_BAD_REQUEST, response.getStatusCode());
}
}
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;
// Test lockdown
JPAUtils utils = JPAUtils.getJPAUtilsInstance();
- assertEquals(utils.dbLockdownIgnoreErrors(), false);
+ assertFalse(utils.dbLockdownIgnoreErrors());
utils.dbLockdown();
fail("Expecting an exception");
}
* ============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.
package org.onap.policy.pap.xacml.rest.util;
import static org.junit.Assert.assertEquals;
+
import org.junit.Test;
public class JsonMessageTest {
* ============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.
* 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;
// Restore the original system property
if (oldProperty != null) {
System.setProperty(systemKey, oldProperty);
- }
- else {
+ } else {
System.clearProperty(systemKey);
}
}
* ============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.
* 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;
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;
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");
try {
filter.destroy();
filter.init(null);
- }
- catch (Exception ex) {
+ } catch (Exception ex) {
fail("Not expecting any exceptions.");
}
}
callDoFilter();
}
- public void callDoFilter(){
+ public void callDoFilter() {
try {
papFilter.doFilter(request, response, filter);
} catch (Exception e) {
}
@Test
- public void testOnPassingInvalidParamters(){
+ public void testOnPassingInvalidParamters() {
Mockito.when(request.getRequestURI()).thenReturn("/pap/");
Mockito.when(request.getHeader("Authorization")).thenReturn("Basic dGVzdHBhcDphbHBoYTE789==");
try {
}
@After
- public void reset(){
+ public void reset() {
// Restore the original system property
if (oldProperty != null) {
System.setProperty(systemKey, oldProperty);
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;
+ }
}
* ============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.
public class MicroserviceHeaderdeFaults implements Serializable {
private static final long serialVersionUID = 1L;
- private static String domain;
-
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="id")
* ============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.
*/
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
* ============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.
*/
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;
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"));
+ }
}
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;
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);
globalRole.setRole("super-admin");
commonClassDao.update(globalRole);
- response.setContentType("application / json");
+ response.setContentType(PolicyUtils.APPLICATION_JSON);
String responseString = mapper.writeValueAsString(commonClassDao.getData(GlobalRoleSettings.class));
public class AutoPushController extends RestrictedBaseController {
private static final Logger logger = FlexLogger.getLogger(AutoPushController.class);
- private static final String UTF8 = "UTF-8";
@Autowired
CommonClassDao commonClassDao;
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();
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);
}
@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();
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);
}
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;
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<>();
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);
}
}
// 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());
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;
protected PolicyRestAdapter policyAdapter = null;
+ /**
+ * prePopulateBRMSRawPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateBRMSRawPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
.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));
}));
}
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;
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;
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;
} 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);
}
} 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);
}
.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));
}));
}
protected PolicyRestAdapter policyAdapter = null;
+ /**
+ * prePopulateClosedLoopPMPolicyData.
+ *
+ * @param policyAdapter PolicyRestAdapter
+ * @param entity PolicyEntity
+ */
public void prePopulateClosedLoopPMPolicyData(PolicyRestAdapter policyAdapter, PolicyEntity entity) {
if (! (policyAdapter.getPolicyData() instanceof PolicyType)) {
return;
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);
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;
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;
}
}
- 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);
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})
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];
// 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);
}
}
+ /**
+ * 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();) {
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;
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;
// 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));
}
}
}
}
}
}
- 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());
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;
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;
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) {
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;
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)) + "}"));
// 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);
}
}
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;
}
}
- 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();
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;
// 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) {
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);
}
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;
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) {
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;
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);
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;
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;
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);
+ 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);
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());
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);
}
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());
+ "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);
}
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());
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());
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);
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;
// 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";
}
public static String getCharacterencoding() {
- return characterEncoding;
+ return PolicyUtils.CHARACTER_ENCODING;
}
public static String getContenttype() {
- return contentType;
+ return PolicyUtils.APPLICATION_JSON;
}
public static String getFile() {
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;
- }
}
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;
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);
import java.io.File;
import java.io.IOException;
-import java.io.PrintWriter;
import java.util.List;
import javax.script.SimpleBindings;
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();
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;
}
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;
} 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) {
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
-import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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;
}
private HttpServletRequest request;
private MockHttpServletResponse response;
+ /**
+ * setUp.
+ *
+ * @throws Exception should not get one
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
private CommonClassDao commonClassDao;
private List<Object> data = null;
+ /**
+ * setUp.
+ *
+ * @throws Exception should not throw one
+ */
@Before
public void setUp() throws Exception {
PolicyController.setjUnit(true);
/**
* 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.
*
*/
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");
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
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();
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 ...)
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
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 {
}
/**
- * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test
+ * Run the PolicyRestAdapter setDataToPolicyRestAdapter(PolicyRestAdapter, JsonNode) method test.
*/
@Test
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);
/**
* Run the ModelAndView getOptimizationTemplateData(HttpServletRequest, HttpServletResponse)
- * method test
+ * method test.
*/
@Test
/**
* Run the ModelAndView getModelServiceVersionData(HttpServletRequest, HttpServletResponse)
- * method test
+ * method test.
*/
@Test
}
/**
- * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test
+ * Run the void prePopulateDCAEMSPolicyData(PolicyRestAdapter, PolicyEntity) method test.
*/
@Test
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();
}
/**
- * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test
+ * Run the void SetMSModelData(HttpServletRequest, HttpServletResponse) method test.
*/
@Test
}
/**
- *
- * @ Get File Stream
- *
+ * @ Get File Stream.
*/
private class MockServletInputStream extends ServletInputStream {
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;
private Path repo;
StdEngine engine = null;
+ /**
+ * setUp.
+ *
+ * @throws Exception should not get one
+ */
@Before
public void setUp() throws Exception {
logger.info("setUp: Entering");
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();
entity.setPolicyName("Config_SampleTest.1.xml");
entity.setPolicyData(policyData);
entity.setScope("com");
+ List<Object> data = new ArrayList<>();
data.add(entity);
when(commonClassDao.getDataByQuery(
# ============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.
#
# 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.
#
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
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
============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.
-->
<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>
<?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>