chang the param file path ,replace id by name

This commit is contained in:
fanfuxiaoran 2014-05-04 11:07:00 +08:00
parent dcf2e9c559
commit df17ad4a2d
97 changed files with 6361 additions and 6366 deletions

View File

@ -1,62 +1,62 @@
package org.bench4q.master;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
*
* @author coderfengyun
*
*/
public class Main {
private static Logger logger = Logger.getLogger(Main.class);
public static int Min_Sample_Cycle_InSecond = 10;
public static int MAX_FAIL_TIMES = 10;
public static int MIN_EXECUTE_INTERVAL_IN_SECONDS = 600;
public static int PICK_CYCLE_IN_SECONDS = 60;
public static String SCRIPT_PARAM_ROOT_FOLDER = "ScriptParameterization";
public static String FILE_SEPARATOR = System.getProperty("file.separator");
public static void main(String[] args) {
try {
MasterServer masterServer = new MasterServer(getPortToServe());
masterServer.start();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public static int getPortToServe() {
int portToUse = 0;
Properties prop = new Properties();
String configFile = "";
try {
InputStream inputStream = Main.class.getClassLoader()
.getResourceAsStream(
"org/bench4q/master/config/ServerPort.properties");
prop.load(inputStream);
portToUse = Integer.parseInt(prop.getProperty("portToServe"));
MAX_FAIL_TIMES = Integer.parseInt(prop.getProperty("maxFailTime"));
MIN_EXECUTE_INTERVAL_IN_SECONDS = Integer.parseInt(prop
.getProperty("minExcuteIntervalInSeconds"));
PICK_CYCLE_IN_SECONDS = Integer.parseInt(prop
.getProperty("pickTestPlanCycleInSeconds"));
Min_Sample_Cycle_InSecond = Integer.parseInt(prop
.getProperty("minSampleCycleInSeconds"));
SCRIPT_PARAM_ROOT_FOLDER = prop
.getProperty("scriptParamRootFolder");
} catch (Exception e) {
portToUse = 8080;
MAX_FAIL_TIMES = 10;
MIN_EXECUTE_INTERVAL_IN_SECONDS = 600;
PICK_CYCLE_IN_SECONDS = 60;
Min_Sample_Cycle_InSecond = 10;
SCRIPT_PARAM_ROOT_FOLDER = "ScriptParameterization";
logger.error("There is no config file for port to serve! where path is "
+ configFile);
}
return portToUse;
}
}
package org.bench4q.master;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
*
* @author coderfengyun
*
*/
public class Main {
private static Logger logger = Logger.getLogger(Main.class);
public static int Min_Sample_Cycle_InSecond = 10;
public static int MAX_FAIL_TIMES = 10;
public static int MIN_EXECUTE_INTERVAL_IN_SECONDS = 600;
public static int PICK_CYCLE_IN_SECONDS = 60;
public static String SCRIPT_PARAM_ROOT_FOLDER = "ScriptParameterization";
public static String FILE_SEPARATOR = System.getProperty("file.separator");
public static void main(String[] args) {
try {
MasterServer masterServer = new MasterServer(getPortToServe());
masterServer.start();
} catch (Exception e) {
e.printStackTrace();
return;
}
}
public static int getPortToServe() {
int portToUse = 0;
Properties prop = new Properties();
String configFile = "";
try {
InputStream inputStream = Main.class.getClassLoader()
.getResourceAsStream(
"org/bench4q/master/config/ServerPort.properties");
prop.load(inputStream);
portToUse = Integer.parseInt(prop.getProperty("portToServe"));
MAX_FAIL_TIMES = Integer.parseInt(prop.getProperty("maxFailTime"));
MIN_EXECUTE_INTERVAL_IN_SECONDS = Integer.parseInt(prop
.getProperty("minExcuteIntervalInSeconds"));
PICK_CYCLE_IN_SECONDS = Integer.parseInt(prop
.getProperty("pickTestPlanCycleInSeconds"));
Min_Sample_Cycle_InSecond = Integer.parseInt(prop
.getProperty("minSampleCycleInSeconds"));
SCRIPT_PARAM_ROOT_FOLDER = prop
.getProperty("scriptParamRootFolder");
} catch (Exception e) {
e.printStackTrace();
MAX_FAIL_TIMES = 10;
MIN_EXECUTE_INTERVAL_IN_SECONDS = 600;
PICK_CYCLE_IN_SECONDS = 60;
Min_Sample_Cycle_InSecond = 10;
SCRIPT_PARAM_ROOT_FOLDER = "ScriptParameterization";
logger.error("There is no config file for port to serve! where path is "
+ configFile);
}
return portToUse;
}
}

View File

@ -1,75 +1,75 @@
package org.bench4q.master;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.servlet.DispatcherServlet;
/**
*
* @author coderfengyun
*
*/
public class MasterServer {
private Server server;
private int port;
private Server getServer() {
return server;
}
private void setServer(Server server) {
this.server = server;
}
private int getPort() {
return port;
}
private void setPort(int port) {
this.port = port;
}
public MasterServer(int port) {
this.setPort(port);
}
public boolean start() {
try {
this.setServer(new Server(this.getPort()));
ServletContextHandler servletContextHandler = new ServletContextHandler();
ServletHolder servletHolder = servletContextHandler.addServlet(
DispatcherServlet.class, "/");
servletHolder
.setInitParameter("contextConfigLocation",
"classpath*:/org/bench4q/master/config/application-context.xml");
servletHolder.setInitOrder(1);
this.getServer().setHandler(servletContextHandler);
this.getServer().start();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean stop() {
try {
if (this.getServer() != null) {
for (Connector connector : this.getServer().getConnectors()) {
if (connector != null) {
connector.shutdown();
}
}
this.getServer().stop();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
this.setServer(null);
}
}
}
package org.bench4q.master;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.web.servlet.DispatcherServlet;
/**
*
* @author coderfengyun
*
*/
public class MasterServer {
private Server server;
private int port;
private Server getServer() {
return server;
}
private void setServer(Server server) {
this.server = server;
}
private int getPort() {
return port;
}
private void setPort(int port) {
this.port = port;
}
public MasterServer(int port) {
this.setPort(port);
}
public boolean start() {
try {
this.setServer(new Server(this.getPort()));
ServletContextHandler servletContextHandler = new ServletContextHandler();
ServletHolder servletHolder = servletContextHandler.addServlet(
DispatcherServlet.class, "/");
servletHolder
.setInitParameter("contextConfigLocation",
"classpath*:/org/bench4q/master/config/application-context.xml");
servletHolder.setInitOrder(1);
this.getServer().setHandler(servletContextHandler);
this.getServer().start();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean stop() {
try {
if (this.getServer() != null) {
for (Connector connector : this.getServer().getConnectors()) {
if (connector != null) {
connector.shutdown();
}
}
this.getServer().stop();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
this.setServer(null);
}
}
}

View File

@ -71,6 +71,11 @@ public class AgentController extends BaseController {
RequestMethod.GET })
@ResponseBody
public AgentResponseModel queryAgentList() {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return setAgentResponseModel(false,
"you don't have the power to get agent from pool!",
new ArrayList<AgentModel>());
}
List<Agent> list = this.getAgentService().loadAgentPoolFromDB();
List<AgentModel> modelList = new ArrayList<AgentModel>();
for (Agent agent : list) {

View File

@ -1,71 +1,71 @@
package org.bench4q.master.api;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.domain.service.auth.AuthenticationManager;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.share.models.ErrorResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
public abstract class BaseController {
private HttpServletRequest request;
private AuthenticationManager authenticationManager;
protected static final String HAVE_NO_POWER = "Have no power";
protected static final String EXCEPTION_HAPPEND = "Exception happened";
private Logger logger = Logger.getLogger(BaseController.class);
protected HttpServletRequest getRequest() {
return request;
}
@Autowired
protected void setRequest(HttpServletRequest request) {
this.request = request;
}
protected AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
@Autowired
protected void setAuthenticationManager(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@ExceptionHandler(Bench4QException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponseModel handleException(Bench4QException e) {
logger.error(ExceptionLog.getStackTrace(e));
return ErrorResponseModel.buildErrorResponse(e.getCode(),
e.getMessage(), e.getResource());
}
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponseModel handleException(RuntimeException e) {
logger.info(ExceptionLog.getStackTrace(e));
logger.info(e.getCause());
return ErrorResponseModel.buildErrorResponse("RUNTIME_EXCEPTION",
e.getMessage(), "");
}
protected User getPrincipal() {
return this.getAuthenticationManager().getPrincipal(this.getRequest());
}
protected boolean checkScope(byte scope) {
return this.getAuthenticationManager().checkScope(this.getRequest(),
scope);
}
}
package org.bench4q.master.api;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.domain.service.auth.AuthenticationManager;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.share.models.ErrorResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
public abstract class BaseController {
private HttpServletRequest request;
private AuthenticationManager authenticationManager;
protected static final String HAVE_NO_POWER = "Have no power";
protected static final String EXCEPTION_HAPPEND = "Exception happened";
private Logger logger = Logger.getLogger(BaseController.class);
protected HttpServletRequest getRequest() {
return request;
}
@Autowired
protected void setRequest(HttpServletRequest request) {
this.request = request;
}
protected AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
@Autowired
protected void setAuthenticationManager(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@ExceptionHandler(Bench4QException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponseModel handleException(Bench4QException e) {
logger.error(ExceptionLog.getStackTrace(e));
return ErrorResponseModel.buildErrorResponse(e.getCode(),
e.getMessage(), e.getResource());
}
@ExceptionHandler(RuntimeException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponseModel handleException(RuntimeException e) {
logger.info(ExceptionLog.getStackTrace(e));
logger.info(e.getCause());
return ErrorResponseModel.buildErrorResponse("RUNTIME_EXCEPTION",
e.getMessage(), "");
}
protected User getPrincipal() {
return this.getAuthenticationManager().getPrincipal(this.getRequest());
}
protected boolean checkScope(byte scope) {
return this.getAuthenticationManager().checkScope(this.getRequest(),
scope);
}
}

View File

@ -1,24 +1,24 @@
package org.bench4q.master.api;
import org.bench4q.master.domain.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/")
public class HomeController extends BaseController {
@RequestMapping(value = { "/" }, method = RequestMethod.GET)
@ResponseBody
public String index() {
User principal = this.getPrincipal();
String userName;
if (principal == null) {
userName = "Anonymous User";
} else {
userName = principal.getUserName();
}
return "Hello [" + userName + "]";
}
package org.bench4q.master.api;
import org.bench4q.master.domain.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/")
public class HomeController extends BaseController {
@RequestMapping(value = { "/" }, method = RequestMethod.GET)
@ResponseBody
public String index() {
User principal = this.getPrincipal();
String userName;
if (principal == null) {
userName = "Anonymous User";
} else {
userName = principal.getUserName();
}
return "Hello [" + userName + "]";
}
}

View File

@ -1,98 +1,98 @@
package org.bench4q.master.api;
import java.util.UUID;
import org.bench4q.master.domain.service.MonitorResultService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.share.models.master.MonitorPhysicalDiskResponseModel;
import org.bench4q.share.models.master.MonitorMemoryResponseModel;
import org.bench4q.share.models.master.MonitorNetworkReponseModel;
import org.bench4q.share.models.master.MonitorProcessorResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/monitorController")
public class MonitorController extends BaseController {
private MonitorResultService monitorResultService;
private MonitorResultService getMonitorResultService() {
return monitorResultService;
}
@Autowired
private void setMonitorResultService(
MonitorResultService monitorResultService) {
this.monitorResultService = monitorResultService;
}
@RequestMapping(value = "/logicDiskMonitorSUTInfo/{testPlanRunId}/{hostName}/{port}/{duationBegin}", method = RequestMethod.GET)
@ResponseBody
public MonitorPhysicalDiskResponseModel logicDiskMonitorSUTInfo(
@PathVariable UUID testPlanRunId, @PathVariable String hostName,
@PathVariable int port, @PathVariable long duationBegin)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/{testPlanRunId}/script/{scriptId}/{fieldName}");
}
MonitorPhysicalDiskResponseModel ret = this.getMonitorResultService()
.physicalDiskDiskResults(testPlanRunId, hostName, port,
duationBegin);
return ret == null ? new MonitorPhysicalDiskResponseModel() : ret;
}
@RequestMapping(value = "/memorySUTInfo", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public MonitorMemoryResponseModel memorySUTInfo(
@RequestParam UUID testPlanRunId, @RequestParam String hostName,
@RequestParam int port, @RequestParam long duationBegin)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/memorySUTInfo");
}
MonitorMemoryResponseModel ret = this.getMonitorResultService()
.loadMemoryModels(testPlanRunId, hostName, port, duationBegin);
return ret == null ? new MonitorMemoryResponseModel() : ret;
}
@RequestMapping(value = "/processorSUTInfo", method = { RequestMethod.GET })
@ResponseBody
public MonitorProcessorResponseModel processorSUTInfo(
@RequestParam UUID testPlanRunId, @RequestParam String hostName,
@RequestParam int port, @RequestParam long duationBegin)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/processorSUTInfo");
}
MonitorProcessorResponseModel ret = this.getMonitorResultService()
.loadProcessorModels(testPlanRunId, hostName, port,
duationBegin);
return ret == null ? new MonitorProcessorResponseModel() : ret;
}
@RequestMapping(value = "/networkInfo", method = { RequestMethod.GET })
@ResponseBody
public MonitorNetworkReponseModel networkInfo(
@RequestParam UUID testPlanRunId, @RequestParam String hostName,
@RequestParam int port, @RequestParam long duationBegin)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/networkInfo");
}
MonitorNetworkReponseModel ret = this.getMonitorResultService()
.loadNetworkInterfaceModels(testPlanRunId, hostName, port,
duationBegin);
return ret == null ? new MonitorNetworkReponseModel() : ret;
}
}
package org.bench4q.master.api;
import java.util.UUID;
import org.bench4q.master.domain.service.MonitorResultService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.share.models.master.MonitorPhysicalDiskResponseModel;
import org.bench4q.share.models.master.MonitorMemoryResponseModel;
import org.bench4q.share.models.master.MonitorNetworkReponseModel;
import org.bench4q.share.models.master.MonitorProcessorResponseModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping(value = "/monitorController")
public class MonitorController extends BaseController {
private MonitorResultService monitorResultService;
private MonitorResultService getMonitorResultService() {
return monitorResultService;
}
@Autowired
private void setMonitorResultService(
MonitorResultService monitorResultService) {
this.monitorResultService = monitorResultService;
}
@RequestMapping(value = "/logicDiskMonitorSUTInfo/{testPlanRunId}/{hostName}/{port}/{duationBegin}", method = RequestMethod.GET)
@ResponseBody
public MonitorPhysicalDiskResponseModel logicDiskMonitorSUTInfo(
@PathVariable UUID testPlanRunId, @PathVariable String hostName,
@PathVariable int port, @PathVariable long duationBegin)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/{testPlanRunId}/script/{scriptId}/{fieldName}");
}
MonitorPhysicalDiskResponseModel ret = this.getMonitorResultService()
.physicalDiskDiskResults(testPlanRunId, hostName, port,
duationBegin);
return ret == null ? new MonitorPhysicalDiskResponseModel() : ret;
}
@RequestMapping(value = "/memorySUTInfo", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public MonitorMemoryResponseModel memorySUTInfo(
@RequestParam UUID testPlanRunId, @RequestParam String hostName,
@RequestParam int port, @RequestParam long duationBegin)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/memorySUTInfo");
}
MonitorMemoryResponseModel ret = this.getMonitorResultService()
.loadMemoryModels(testPlanRunId, hostName, port, duationBegin);
return ret == null ? new MonitorMemoryResponseModel() : ret;
}
@RequestMapping(value = "/processorSUTInfo", method = { RequestMethod.GET })
@ResponseBody
public MonitorProcessorResponseModel processorSUTInfo(
@RequestParam UUID testPlanRunId, @RequestParam String hostName,
@RequestParam int port, @RequestParam long duationBegin)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/processorSUTInfo");
}
MonitorProcessorResponseModel ret = this.getMonitorResultService()
.loadProcessorModels(testPlanRunId, hostName, port,
duationBegin);
return ret == null ? new MonitorProcessorResponseModel() : ret;
}
@RequestMapping(value = "/networkInfo", method = { RequestMethod.GET })
@ResponseBody
public MonitorNetworkReponseModel networkInfo(
@RequestParam UUID testPlanRunId, @RequestParam String hostName,
@RequestParam int port, @RequestParam long duationBegin)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/networkInfo");
}
MonitorNetworkReponseModel ret = this.getMonitorResultService()
.loadNetworkInterfaceModels(testPlanRunId, hostName, port,
duationBegin);
return ret == null ? new MonitorNetworkReponseModel() : ret;
}
}

View File

@ -7,7 +7,6 @@ import org.bench4q.master.domain.service.PluginService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.plugin.BehaviorInfoModel;
import org.bench4q.share.models.master.plugin.PluginResponseModel;
import org.bench4q.share.models.master.plugin.PluginUIModel;
@ -79,7 +78,7 @@ public class PluginController extends BaseController {
@RequestMapping(value = "/loadBehaviors/{pluginName}", method = {
RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public PluginResponseModel getMethods(
public PluginResponseModel getBehaviorsInPlugin(
@PathVariable("pluginName") String pluginName)
throws Bench4QException {
@ -107,8 +106,6 @@ public class PluginController extends BaseController {
pluginResponseModel.setBehaviorInfoModels(behaviorInfoModels);
}
logger.info(MarshalHelper.marshal(PluginResponseModel.class,
pluginResponseModel));
return pluginResponseModel;
} catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));

View File

@ -1,116 +1,116 @@
package org.bench4q.master.api;
import java.util.ArrayList;
import java.util.List;
import org.bench4q.master.domain.entity.Port;
import org.bench4q.master.domain.factory.BusinessModelMapFactory;
import org.bench4q.master.domain.service.PortPoolService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.share.models.master.OrganizeRecordPortResponseModel;
import org.bench4q.share.models.master.PortModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/RecordPort")
public class RecordPortController extends BaseController {
private PortPoolService portPoolService = new PortPoolService();
private static Object syncObject = new Object();
public PortPoolService getPortPoolService() {
return portPoolService;
}
@Autowired
private void setPortPoolService(PortPoolService portPoolService) {
this.portPoolService = portPoolService;
}
public static Object getSyncObject() {
return syncObject;
}
public static void setSyncObject(Object syncObject) {
RecordPortController.syncObject = syncObject;
}
@RequestMapping(value = "/addPortToPortPool", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public OrganizeRecordPortResponseModel addPortToPortPool(
@RequestParam int port) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false,
"you don't hava the power to add port to pool!",
new ArrayList<PortModel>());
}
if (!this.getPortPoolService().addPortToDBPool(port)) {
return _buildResponseModel(false, "add to DB pool fails",
new ArrayList<PortModel>());
}
return _buildResponseModel(true, "", new ArrayList<PortModel>());
}
@RequestMapping(value = "/removePortFromPool", method = RequestMethod.POST)
@ResponseBody
public OrganizeRecordPortResponseModel removePortFromPool(
@RequestParam int portId) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false,
"you don't hava the power to remove port from pool!",
new ArrayList<PortModel>());
}
if (!this.getPortPoolService().removePortFromDBPool(portId)) {
return _buildResponseModel(false, "remove from local fails",
new ArrayList<PortModel>());
}
return _buildResponseModel(true, "", new ArrayList<PortModel>());
}
@RequestMapping(value = "/loadPortList", method = RequestMethod.POST)
@ResponseBody
public OrganizeRecordPortResponseModel loadPortList() {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false,
"you don't hava the power to load!",
new ArrayList<PortModel>());
}
List<PortModel> portModels = new ArrayList<PortModel>();
for (Port port : this.portPoolService.loadPortList()) {
portModels.add(BusinessModelMapFactory.toModel(port));
}
return this._buildResponseModel(true, "", portModels);
}
@RequestMapping(value = "/editPort", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OrganizeRecordPortResponseModel editPort(@RequestParam PortModel port) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false, "you don't have power to edit",
new ArrayList<PortModel>());
}
return this._buildResponseModel(
this.getPortPoolService().editPort(
BusinessModelMapFactory.toBusiness(port)), "",
new ArrayList<PortModel>());
}
private OrganizeRecordPortResponseModel _buildResponseModel(
boolean success, String failString, List<PortModel> ports) {
OrganizeRecordPortResponseModel result = new OrganizeRecordPortResponseModel();
result.setSuccess(success);
result.setFailCauseString(failString);
result.setPortModels(ports);
return result;
}
}
package org.bench4q.master.api;
import java.util.ArrayList;
import java.util.List;
import org.bench4q.master.domain.entity.Port;
import org.bench4q.master.domain.factory.BusinessModelMapFactory;
import org.bench4q.master.domain.service.PortPoolService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.share.models.master.OrganizeRecordPortResponseModel;
import org.bench4q.share.models.master.PortModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/RecordPort")
public class RecordPortController extends BaseController {
private PortPoolService portPoolService = new PortPoolService();
private static Object syncObject = new Object();
public PortPoolService getPortPoolService() {
return portPoolService;
}
@Autowired
private void setPortPoolService(PortPoolService portPoolService) {
this.portPoolService = portPoolService;
}
public static Object getSyncObject() {
return syncObject;
}
public static void setSyncObject(Object syncObject) {
RecordPortController.syncObject = syncObject;
}
@RequestMapping(value = "/addPortToPortPool", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public OrganizeRecordPortResponseModel addPortToPortPool(
@RequestParam int port) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false,
"you don't hava the power to add port to pool!",
new ArrayList<PortModel>());
}
if (!this.getPortPoolService().addPortToDBPool(port)) {
return _buildResponseModel(false, "add to DB pool fails",
new ArrayList<PortModel>());
}
return _buildResponseModel(true, "", new ArrayList<PortModel>());
}
@RequestMapping(value = "/removePortFromPool", method = RequestMethod.POST)
@ResponseBody
public OrganizeRecordPortResponseModel removePortFromPool(
@RequestParam int portId) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false,
"you don't hava the power to remove port from pool!",
new ArrayList<PortModel>());
}
if (!this.getPortPoolService().removePortFromDBPool(portId)) {
return _buildResponseModel(false, "remove from local fails",
new ArrayList<PortModel>());
}
return _buildResponseModel(true, "", new ArrayList<PortModel>());
}
@RequestMapping(value = "/loadPortList", method = RequestMethod.POST)
@ResponseBody
public OrganizeRecordPortResponseModel loadPortList() {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false,
"you don't hava the power to load!",
new ArrayList<PortModel>());
}
List<PortModel> portModels = new ArrayList<PortModel>();
for (Port port : this.portPoolService.loadPortList()) {
portModels.add(BusinessModelMapFactory.toModel(port));
}
return this._buildResponseModel(true, "", portModels);
}
@RequestMapping(value = "/editPort", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OrganizeRecordPortResponseModel editPort(@RequestParam PortModel port) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false, "you don't have power to edit",
new ArrayList<PortModel>());
}
return this._buildResponseModel(
this.getPortPoolService().editPort(
BusinessModelMapFactory.toBusiness(port)), "",
new ArrayList<PortModel>());
}
private OrganizeRecordPortResponseModel _buildResponseModel(
boolean success, String failString, List<PortModel> ports) {
OrganizeRecordPortResponseModel result = new OrganizeRecordPortResponseModel();
result.setSuccess(success);
result.setFailCauseString(failString);
result.setPortModels(ports);
return result;
}
}

View File

@ -1,297 +1,297 @@
package org.bench4q.master.api;
import java.io.File;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.Port;
import org.bench4q.master.domain.entity.Script;
import org.bench4q.master.domain.factory.BusinessModelMapFactory;
import org.bench4q.master.domain.service.PortPoolService;
import org.bench4q.master.domain.service.ScriptService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.recorder.ScriptCapturer;
import org.bench4q.share.models.master.OperateScriptServerResponseModel;
import org.bench4q.share.models.master.ScriptModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/RecordScript")
public class ScriptController extends BaseController {
private ScriptCapturer scriptCapturer;
private ScriptService scriptService;
private PortPoolService portPoolService = new PortPoolService();
private static final Object PORT_LOCK = new Object();
private Logger logger = Logger.getLogger(ScriptController.class);
private ScriptCapturer getScriptCapturer() {
return scriptCapturer;
}
@Autowired
private void setScriptCapturer(ScriptCapturer scriptCapturer) {
this.scriptCapturer = scriptCapturer;
}
private ScriptService getScriptService() {
return scriptService;
}
@Autowired
private void setScriptService(ScriptService scriptService) {
this.scriptService = scriptService;
}
private PortPoolService getPortPoolService() {
return portPoolService;
}
@Autowired
private void setPortPoolService(PortPoolService portPoolService) {
this.portPoolService = portPoolService;
}
@RequestMapping(value = "/startScriptRecordServer", method = {
RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel startScriptRecordServer()
throws UnknownHostException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildReponseModel(false,
"has no power for recording script!!!", "", -1, null, null,
null);
}
Port port = new Port();
synchronized (PORT_LOCK) {
port = this.getPortPoolService().getAPortNotInUse();
if (port == null) {
return buildReponseModel(false, "port is in use!", "", -1,
null, null, null);
}
}
UUID uuid = UUID.randomUUID();
this.getScriptCapturer().startRecord(port.getPort(),
buildScriptSavePath(), uuid.toString());
return buildReponseModel(true, "", this.getScriptCapturer()
.getIpHttpCaptureServerAdress(), port.getPort(), null, null,
uuid.toString());
}
private String buildScriptSavePath() {
String dirString = "Scripts" + System.getProperty("file.separator")
+ this.getPrincipal().getUserName()
+ System.getProperty("file.separator")
+ new SimpleDateFormat("yyyyMMdd").format(new Date());
File dirFile = new File(dirString);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
return dirString;
}
@RequestMapping(value = "/stopScriptRecordServer", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public OperateScriptServerResponseModel stopScriptRecordServer(
@RequestParam int port, @RequestParam String fileNameUUID) {
if (!checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildReponseModel(false,
"has no power for stopScriptCapture!!!", "", -1, null,
null, null);
}
this.getScriptCapturer().stopCurrentRecord(port);
synchronized (PORT_LOCK) {
this.getPortPoolService().backPort(port);
}
return buildReponseModel(true, "RecordServer stop", "", port, null,
null, fileNameUUID);
}
@RequestMapping(value = "/saveScriptToDB", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel saveScriptToDB(
@RequestParam String scriptName, @RequestParam int port,
@RequestParam String fileNameUUID) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildReponseModel(false,
"saveScriptToDB check your scope fail!", "", -1, null,
null, null);
}
File file = new File(buildScriptSavePath()
+ System.getProperty("file.separator") + fileNameUUID + ".xml");
if (!file.exists()) {
return buildReponseModel(false, "no that script", null, -1, null,
null, fileNameUUID);
}
try {
String content = FileUtils.readFileToString(file);
logger.info("when saveToDB, scriptContent is " + content);
boolean success = this.getScriptService().saveScript(scriptName,
this.getPrincipal().getId(), content, null);
// this.getUserService().add
return buildReponseModel(success, "Save to DataBase!!", "", port,
null, null, null);
} catch (Exception e) {
return buildReponseModel(false, "exception when read from file",
null, -1, null, null, fileNameUUID);
}
}
@RequestMapping(value = "/uploadScript/{scriptName}", method = {
RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel uploadScriptToDB(
@PathVariable String scriptName,
@RequestParam String scenarioModel,
@RequestParam(value = "paramFiles[]", required = false) List<MultipartFile> paramFiles)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER, HAVE_NO_POWER
+ "for upload a script", "/uploadScript");
}
try {
boolean success = this.getScriptService().saveScript(scriptName,
this.getPrincipal().getId(), scenarioModel, paramFiles);
logger.info("upload script:" + scenarioModel);
return buildReponseModel(success, null, null, -1, null, null, null);
} catch (Exception e) {
this.logger.error(ExceptionLog.getStackTrace(e));
return buildReponseModel(false,
"The script is not in the right format", null, -1, null,
null, null);
}
}
@RequestMapping(value = "/loadScriptList", method = { RequestMethod.POST,
RequestMethod.GET })
@ResponseBody
public OperateScriptServerResponseModel loadScriptList() {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
List<Script> scripts = this.getScriptService().loadScripts(
this.getPrincipal());
return this.buildReponseModel(true, null, null, 0,
dealWithCollection(scripts), null, null);
}
@RequestMapping(value = "/queryScriptsByDate", method = RequestMethod.POST)
@ResponseBody
public OperateScriptServerResponseModel queryScriptsByDate(
@RequestParam Date startDate, @RequestParam Date endDate) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
List<Script> scripts = this.getScriptService()
.queryScriptsByCreateTime(startDate, endDate,
this.getPrincipal());
return this.buildReponseModel(true, null, null, 0,
dealWithCollection(scripts), null, null);
}
private List<ScriptModel> dealWithCollection(Collection<Script> scripts) {
List<ScriptModel> scriptModels = new ArrayList<ScriptModel>();
for (Script script : scripts) {
scriptModels.add(BusinessModelMapFactory.toModel(script));
}
return scriptModels;
}
@RequestMapping(value = "/queryScriptById", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel queryScriptById(
@RequestParam int scriptId) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
return this.buildReponseModel(true, null, null, 0, null,
BusinessModelMapFactory.toModel(this.getScriptService()
.getScript(scriptId)), null);
}
@RequestMapping(value = "/queryScriptByName", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel queryScriptByName(
@RequestParam String name) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
return this.buildReponseModel(true, null, null, 0, null,
BusinessModelMapFactory.toModel(this.getScriptService()
.getScriptByName(name)), null);
}
@RequestMapping(value = "/deleteScript", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel deleteScript(
@RequestParam int scriptId) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
return this.buildReponseModel(
this.getScriptService().deleteScript(scriptId,
this.getPrincipal().getId()), "", "", 0, null, null,
null);
}
@RequestMapping(value = "updateScript/{scriptId}", method = {
RequestMethod.GET, RequestMethod.PUT })
@ResponseBody
public OperateScriptServerResponseModel updateScript(
@PathVariable int scriptId, @RequestBody String content) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
Logger.getLogger(ScriptController.class).info("no power");
return null;
}
return this.buildReponseModel(
this.getScriptService().alterScriptContent(scriptId,
this.getPrincipal().getId(), content), "", "", 0, null,
null, null);
}
private OperateScriptServerResponseModel buildReponseModel(
boolean isSuccess, String failCauseString, String hostName,
int port, List<ScriptModel> scriptModels, ScriptModel scriptModel,
String fileName) {
OperateScriptServerResponseModel responseModel = new OperateScriptServerResponseModel();
responseModel.setSuccess(isSuccess);
responseModel.setFailCauseString(failCauseString);
responseModel.setHostName(hostName);
responseModel.setPort(port);
responseModel.setFileName(fileName);
if (scriptModels == null || scriptModels.size() == 0) {
scriptModels = new ArrayList<ScriptModel>();
scriptModels.add(scriptModel);
}
responseModel.setScriptModels(scriptModels);
return responseModel;
}
}
package org.bench4q.master.api;
import java.io.File;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.Port;
import org.bench4q.master.domain.entity.Script;
import org.bench4q.master.domain.factory.BusinessModelMapFactory;
import org.bench4q.master.domain.service.PortPoolService;
import org.bench4q.master.domain.service.ScriptService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.recorder.ScriptCapturer;
import org.bench4q.share.models.master.OperateScriptServerResponseModel;
import org.bench4q.share.models.master.ScriptModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
@RequestMapping("/script")
public class ScriptController extends BaseController {
private ScriptCapturer scriptCapturer;
private ScriptService scriptService;
private PortPoolService portPoolService = new PortPoolService();
private static final Object PORT_LOCK = new Object();
private Logger logger = Logger.getLogger(ScriptController.class);
private ScriptCapturer getScriptCapturer() {
return scriptCapturer;
}
@Autowired
private void setScriptCapturer(ScriptCapturer scriptCapturer) {
this.scriptCapturer = scriptCapturer;
}
private ScriptService getScriptService() {
return scriptService;
}
@Autowired
private void setScriptService(ScriptService scriptService) {
this.scriptService = scriptService;
}
private PortPoolService getPortPoolService() {
return portPoolService;
}
@Autowired
private void setPortPoolService(PortPoolService portPoolService) {
this.portPoolService = portPoolService;
}
@RequestMapping(value = "/startScriptRecordServer", method = {
RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel startScriptRecordServer()
throws UnknownHostException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildReponseModel(false,
"has no power for recording script!!!", "", -1, null, null,
null);
}
Port port = new Port();
synchronized (PORT_LOCK) {
port = this.getPortPoolService().getAPortNotInUse();
if (port == null) {
return buildReponseModel(false, "port is in use!", "", -1,
null, null, null);
}
}
UUID uuid = UUID.randomUUID();
this.getScriptCapturer().startRecord(port.getPort(),
buildScriptSavePath(), uuid.toString());
return buildReponseModel(true, "", this.getScriptCapturer()
.getIpHttpCaptureServerAdress(), port.getPort(), null, null,
uuid.toString());
}
private String buildScriptSavePath() {
String dirString = "Scripts" + System.getProperty("file.separator")
+ this.getPrincipal().getUserName()
+ System.getProperty("file.separator")
+ new SimpleDateFormat("yyyyMMdd").format(new Date());
File dirFile = new File(dirString);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
return dirString;
}
@RequestMapping(value = "/stopScriptRecordServer", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public OperateScriptServerResponseModel stopScriptRecordServer(
@RequestParam int port, @RequestParam String fileNameUUID) {
if (!checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildReponseModel(false,
"has no power for stopScriptCapture!!!", "", -1, null,
null, null);
}
this.getScriptCapturer().stopCurrentRecord(port);
synchronized (PORT_LOCK) {
this.getPortPoolService().backPort(port);
}
return buildReponseModel(true, "RecordServer stop", "", port, null,
null, fileNameUUID);
}
@RequestMapping(value = "/saveScriptToDB", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel saveScriptToDB(
@RequestParam String scriptName, @RequestParam int port,
@RequestParam String fileNameUUID) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildReponseModel(false,
"saveScriptToDB check your scope fail!", "", -1, null,
null, null);
}
File file = new File(buildScriptSavePath()
+ System.getProperty("file.separator") + fileNameUUID + ".xml");
if (!file.exists()) {
return buildReponseModel(false, "no that script", null, -1, null,
null, fileNameUUID);
}
try {
String content = FileUtils.readFileToString(file);
logger.info("when saveToDB, scriptContent is " + content);
boolean success = this.getScriptService().saveScript(scriptName,
this.getPrincipal().getId(), content, null);
// this.getUserService().add
return buildReponseModel(success, "Save to DataBase!!", "", port,
null, null, null);
} catch (Exception e) {
return buildReponseModel(false, "exception when read from file",
null, -1, null, null, fileNameUUID);
}
}
@RequestMapping(value = "/uploadScript/{scriptName}", method = {
RequestMethod.PUT, RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel uploadScriptToDB(
@PathVariable String scriptName,
@RequestParam String scenarioModel,
@RequestParam(value = "paramFiles[]", required = false) List<MultipartFile> paramFiles)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER, HAVE_NO_POWER
+ "for upload a script", "/uploadScript");
}
try {
boolean success = this.getScriptService().saveScript(scriptName,
this.getPrincipal().getId(), scenarioModel, paramFiles);
logger.info("upload script:" + scenarioModel);
return buildReponseModel(success, null, null, -1, null, null, null);
} catch (Exception e) {
this.logger.error(ExceptionLog.getStackTrace(e));
return buildReponseModel(false,
"The script is not in the right format", null, -1, null,
null, null);
}
}
@RequestMapping(value = "/loadScriptList", method = { RequestMethod.POST,
RequestMethod.GET })
@ResponseBody
public OperateScriptServerResponseModel loadScriptList() {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
List<Script> scripts = this.getScriptService().loadScripts(
this.getPrincipal());
return this.buildReponseModel(true, null, null, 0,
dealWithCollection(scripts), null, null);
}
@RequestMapping(value = "/queryScriptsByDate", method = RequestMethod.POST)
@ResponseBody
public OperateScriptServerResponseModel queryScriptsByDate(
@RequestParam Date startDate, @RequestParam Date endDate) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
List<Script> scripts = this.getScriptService()
.queryScriptsByCreateTime(startDate, endDate,
this.getPrincipal());
return this.buildReponseModel(true, null, null, 0,
dealWithCollection(scripts), null, null);
}
private List<ScriptModel> dealWithCollection(Collection<Script> scripts) {
List<ScriptModel> scriptModels = new ArrayList<ScriptModel>();
for (Script script : scripts) {
scriptModels.add(BusinessModelMapFactory.toModel(script));
}
return scriptModels;
}
@RequestMapping(value = "/queryScriptById", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel queryScriptById(
@RequestParam int scriptId) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
return this.buildReponseModel(true, null, null, 0, null,
BusinessModelMapFactory.toModel(this.getScriptService()
.getScript(scriptId)), null);
}
@RequestMapping(value = "/queryScriptByName", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel queryScriptByName(
@RequestParam String name) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
return this.buildReponseModel(true, null, null, 0, null,
BusinessModelMapFactory.toModel(this.getScriptService()
.getScriptByName(name)), null);
}
@RequestMapping(value = "/deleteScript", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseBody
public OperateScriptServerResponseModel deleteScript(
@RequestParam int scriptId) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
return this.buildReponseModel(
this.getScriptService().deleteScript(scriptId,
this.getPrincipal().getId()), "", "", 0, null, null,
null);
}
@RequestMapping(value = "updateScript/{scriptId}", method = {
RequestMethod.GET, RequestMethod.POST ,RequestMethod.PUT})
@ResponseBody
public OperateScriptServerResponseModel updateScript(
@PathVariable int scriptId, @RequestBody String content) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
Logger.getLogger(ScriptController.class).info("no power");
return null;
}
return this.buildReponseModel(
this.getScriptService().alterScriptContent(scriptId,
this.getPrincipal().getId(), content), "", "", 0, null,
null, null);
}
private OperateScriptServerResponseModel buildReponseModel(
boolean isSuccess, String failCauseString, String hostName,
int port, List<ScriptModel> scriptModels, ScriptModel scriptModel,
String fileName) {
OperateScriptServerResponseModel responseModel = new OperateScriptServerResponseModel();
responseModel.setSuccess(isSuccess);
responseModel.setFailCauseString(failCauseString);
responseModel.setHostName(hostName);
responseModel.setPort(port);
responseModel.setFileName(fileName);
if (scriptModels == null || scriptModels.size() == 0) {
scriptModels = new ArrayList<ScriptModel>();
scriptModels.add(scriptModel);
}
responseModel.setScriptModels(scriptModels);
return responseModel;
}
}

View File

@ -1,295 +1,287 @@
package org.bench4q.master.api;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.TestPlan;
import org.bench4q.master.domain.factory.BusinessModelMapFactory;
import org.bench4q.master.domain.service.TestPlanEngine;
import org.bench4q.master.domain.service.TestPlanScriptResultService;
import org.bench4q.master.domain.service.TestPlanService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.domain.service.report.ReportService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.share.enums.master.TestPlanStatus;
import org.bench4q.share.models.master.MonitorModel;
import org.bench4q.share.models.master.TestPlanScriptBriefResultModel;
import org.bench4q.share.models.master.TestPlanModel;
import org.bench4q.share.models.master.TestPlanDBModel;
import org.bench4q.share.models.master.TestPlanResponseModel;
import org.bench4q.share.models.master.TestPlanResultModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
@RequestMapping("/testPlan")
public class TestPlanController extends BaseController {
private TestPlanEngine testPlanRunner;
private TestPlanService testPlanService;
private ReportService reportService;
private TestPlanScriptResultService testPlanScriptResultService;
private BusinessModelMapFactory businessMapFactory;
private Logger logger = Logger.getLogger(TestPlanController.class);
private TestPlanEngine getTestPlanRunner() {
return testPlanRunner;
}
@Autowired
private void setTestPlanRunner(TestPlanEngine testPlanRunner) {
this.testPlanRunner = testPlanRunner;
}
private TestPlanService getTestPlanService() {
return this.testPlanService;
}
@Autowired
private void setTestPlanService(TestPlanService testPlanService) {
this.testPlanService = testPlanService;
}
private ReportService getReportService() {
return reportService;
}
@Autowired
private void setReportService(ReportService reportService) {
this.reportService = reportService;
}
private BusinessModelMapFactory getBusinessMapFactory() {
return businessMapFactory;
}
@Autowired
private void setBusinessMapFactory(
BusinessModelMapFactory businessMapFactory) {
this.businessMapFactory = businessMapFactory;
}
private TestPlanScriptResultService getTestPlanScriptResultService() {
return testPlanScriptResultService;
}
@Autowired
private void setTestPlanScriptResultService(
TestPlanScriptResultService testPlanScriptResultService) {
this.testPlanScriptResultService = testPlanScriptResultService;
}
@RequestMapping(value = "/runTestPlanWithTestPlanModel", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanResultModel runTestPlanWithTestPlanModel(
@RequestBody TestPlanModel testPlanBusinessModel)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER,
"You don't have enough power to run a test plan!",
"/runTestPlanWithTestPlanModel");
}
UUID testPlanRunID = this.getTestPlanRunner().runWith(
testPlanBusinessModel, this.getPrincipal());
if (testPlanRunID == null) {
throw new Bench4QException("TestPlan_Commit_Error",
"There is an exception when commit the test plan",
"/runTestPlanWithTestPlanModel");
}
return buildResponseModel(this.getTestPlanService()
.queryTestPlanStatus(testPlanRunID), testPlanRunID, null,
testPlanBusinessModel.getMonitorModels());
}
private TestPlanResultModel buildResponseModel(
TestPlanStatus currentStatus, UUID testPlanId,
List<Integer> scriptIds, List<MonitorModel> monitorModels) {
TestPlanResultModel result = new TestPlanResultModel();
result.setCurrentStatus(currentStatus);
result.setTestPlanId(testPlanId);
result.setScriptIds(scriptIds);
result.setMonitorModels(monitorModels);
return result;
}
@RequestMapping(value = "/getRunningInfo", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanResultModel getTestPlanRunningInfo(
@RequestParam UUID testPlanId) throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER,
"You have not power to get test plan running info",
"/getRunningInfo");
}
return this.getTestPlanService().buildResultModel(testPlanId);
}
@RequestMapping(value = "/scriptBrief/{testPlanId}/{scriptId}/{duationBegin}", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanScriptBriefResultModel getScriptBrief(
@PathVariable UUID testPlanId, @PathVariable int scriptId,
@PathVariable long duationBegin) throws Bench4QException,
NullPointerException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER,
"You have not power to get test plan script brief",
"/getRunningInfo");
}
List<ScriptBriefResultModel> scriptBriefResultModels = this
.getTestPlanScriptResultService().loadScriptBriefWithDuation(
testPlanId, scriptId, duationBegin);
TestPlanScriptBriefResultModel ret = new TestPlanScriptBriefResultModel();
ret.setScriptBriefResultModels(scriptBriefResultModels);
return ret;
}
@RequestMapping(value = "/getBehaviorsBrief/{testPlanRunID}/{scriptId}")
@ResponseBody
public ScriptBehaviorsBriefModel getBehaviorsBrief(
@PathVariable UUID testPlanRunID, @PathVariable int scriptId)
throws Bench4QException, NullPointerException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER, EXCEPTION_HAPPEND
+ "when get behaviors's brief", "/getBehaviorsBrief");
}
ScriptBehaviorsBriefModel result = this
.getTestPlanScriptResultService().getScriptBehaviorsBrief(
testPlanRunID, scriptId);
return result;
}
@RequestMapping(value = "/behaviorBrief/{testPlanRunID}/{scriptId}/{behaviorId}/{duationBegin}")
@ResponseBody
public ScriptBehaviorsBriefModel getBehaviorBrief(
@PathVariable UUID testPlanRunID, @PathVariable int scriptId,
@PathVariable int behaviorId, @PathVariable long duactionBegin)
throws Bench4QException {
return null;
}
@RequestMapping(value = "/pagesBrief/{testPlanRunId}/{scriptId}")
@ResponseBody
public ScriptPagesBriefModel getPagesBrief(
@PathVariable UUID testPlanRunId, @PathVariable int scriptId)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER, EXCEPTION_HAPPEND
+ "when get behaviors's brief", "/getBehaviorsBrief");
}
ScriptPagesBriefModel pagesBriefModel = this
.getTestPlanScriptResultService().getScriptPagesBrief(
testPlanRunId, scriptId);
return pagesBriefModel;
}
@RequestMapping(value = "/loadTestPlans", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanResponseModel loadTestPlans() {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildTestPlanResponseModel(false, "no scope", null);
}
List<TestPlan> testPlanDBs = this.testPlanService.loadTestPlans(this
.getPrincipal());
return testPlanDBs == null ? buildTestPlanResponseModel(false,
"exception", null) : buildTestPlanResponseModel(true, null,
testPlanDBs);
}
@RequestMapping(value = "/queryTestPlan/{runId}", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanDBModel queryTestPlan(@PathVariable UUID runId)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER, HAVE_NO_POWER,
"/queryTestPlan/{runId}");
}
return this.getTestPlanService().getTestPlanDBModel(runId);
}
@RequestMapping(value = "/removeTestPlanFromPool", method = {
RequestMethod.GET, RequestMethod.POST })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanResponseModel removeTestPlanFromPool(int testPlanId) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildTestPlanResponseModel(false, "no scope", null);
}
return buildTestPlanResponseModel(
this.testPlanService.removeTestPlanInDB(testPlanId), null, null);
}
private TestPlanResponseModel buildTestPlanResponseModel(boolean success,
String failCause, List<TestPlan> testPlanDBs) {
TestPlanResponseModel result = new TestPlanResponseModel();
result.setSuccess(success);
result.setFailCause(failCause);
List<TestPlanDBModel> modelList = new ArrayList<TestPlanDBModel>();
if (testPlanDBs != null) {
for (TestPlan testPlanDB : testPlanDBs) {
modelList.add(this.getBusinessMapFactory().toModel(testPlanDB));
}
}
result.setTestPlanDBModels(modelList);
return result;
}
@RequestMapping(value = "/getTestPlanReport", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public void getTestPlanReport(HttpServletResponse response,
@RequestParam UUID testPlanRunID) throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER,
"You have no power to get test plan report",
"/getTestPlanReport");
}
buildFileStream(response, testPlanRunID, this.getReportService()
.createReport(testPlanRunID));
}
private void buildFileStream(HttpServletResponse response,
UUID testPlanRunID, byte[] pdfBuffer) {
try {
ServletOutputStream outputStream = response.getOutputStream();
response.reset();
response.setHeader("Content-disposition", "attachment; filename=\""
+ testPlanRunID.toString() + ".pdf\"");
response.addHeader("Content-Length", "" + pdfBuffer.length);
this.logger.info("report of test plan " + testPlanRunID.toString()
+ " length is: " + pdfBuffer.length);
response.setContentType("application/pdf");
outputStream.write(pdfBuffer);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
package org.bench4q.master.api;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.TestPlan;
import org.bench4q.master.domain.factory.BusinessModelMapFactory;
import org.bench4q.master.domain.service.TestPlanEngine;
import org.bench4q.master.domain.service.TestPlanScriptResultService;
import org.bench4q.master.domain.service.TestPlanService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.domain.service.report.ReportService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.share.enums.master.TestPlanStatus;
import org.bench4q.share.models.master.MonitorModel;
import org.bench4q.share.models.master.TestPlanScriptBriefResultModel;
import org.bench4q.share.models.master.TestPlanModel;
import org.bench4q.share.models.master.TestPlanDBModel;
import org.bench4q.share.models.master.TestPlanResponseModel;
import org.bench4q.share.models.master.TestPlanResultModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
@RequestMapping("/testPlan")
public class TestPlanController extends BaseController {
private TestPlanEngine testPlanRunner;
private TestPlanService testPlanService;
private ReportService reportService;
private TestPlanScriptResultService testPlanScriptResultService;
private BusinessModelMapFactory businessMapFactory;
private Logger logger = Logger.getLogger(TestPlanController.class);
private TestPlanEngine getTestPlanRunner() {
return testPlanRunner;
}
@Autowired
private void setTestPlanRunner(TestPlanEngine testPlanRunner) {
this.testPlanRunner = testPlanRunner;
}
private TestPlanService getTestPlanService() {
return this.testPlanService;
}
@Autowired
private void setTestPlanService(TestPlanService testPlanService) {
this.testPlanService = testPlanService;
}
private ReportService getReportService() {
return reportService;
}
@Autowired
private void setReportService(ReportService reportService) {
this.reportService = reportService;
}
private BusinessModelMapFactory getBusinessMapFactory() {
return businessMapFactory;
}
@Autowired
private void setBusinessMapFactory(
BusinessModelMapFactory businessMapFactory) {
this.businessMapFactory = businessMapFactory;
}
private TestPlanScriptResultService getTestPlanScriptResultService() {
return testPlanScriptResultService;
}
@Autowired
private void setTestPlanScriptResultService(
TestPlanScriptResultService testPlanScriptResultService) {
this.testPlanScriptResultService = testPlanScriptResultService;
}
@RequestMapping(value = "/runTestPlanWithTestPlanModel", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanResultModel runTestPlanWithTestPlanModel(
@RequestBody TestPlanModel testPlanBusinessModel)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER,
"You don't have enough power to run a test plan!",
"/runTestPlanWithTestPlanModel");
}
UUID testPlanRunID = this.getTestPlanRunner().runWith(
testPlanBusinessModel, this.getPrincipal());
if (testPlanRunID == null) {
throw new Bench4QException("TestPlan_Commit_Error",
"There is an exception when commit the test plan",
"/runTestPlanWithTestPlanModel");
}
return buildResponseModel(this.getTestPlanService()
.queryTestPlanStatus(testPlanRunID), testPlanRunID, null,
testPlanBusinessModel.getMonitorModels());
}
private TestPlanResultModel buildResponseModel(
TestPlanStatus currentStatus, UUID testPlanId,
List<Integer> scriptIds, List<MonitorModel> monitorModels) {
TestPlanResultModel result = new TestPlanResultModel();
result.setCurrentStatus(currentStatus);
result.setTestPlanId(testPlanId);
result.setScriptIds(scriptIds);
result.setMonitorModels(monitorModels);
return result;
}
@RequestMapping(value = "/getRunningInfo", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanResultModel getTestPlanRunningInfo(
@RequestParam UUID testPlanId) throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER,
"You have not power to get test plan running info",
"/getRunningInfo");
}
return this.getTestPlanService().buildResultModel(testPlanId);
}
@RequestMapping(value = "/scriptBrief/{testPlanId}/{scriptId}/{duationBegin}", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanScriptBriefResultModel getScriptBrief(
@PathVariable UUID testPlanId, @PathVariable int scriptId,
@PathVariable long duationBegin) throws Bench4QException,
NullPointerException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER,
"You have not power to get test plan script brief",
"/getRunningInfo");
}
List<ScriptBriefResultModel> scriptBriefResultModels = this
.getTestPlanScriptResultService().loadScriptBriefWithDuation(
testPlanId, scriptId, duationBegin);
TestPlanScriptBriefResultModel ret = new TestPlanScriptBriefResultModel();
ret.setScriptBriefResultModels(scriptBriefResultModels);
return ret;
}
@RequestMapping(value = "/getBehaviorsBrief/{testPlanRunID}/{scriptId}")
@ResponseBody
public ScriptBehaviorsBriefModel getBehaviorsBrief(
@PathVariable UUID testPlanRunID, @PathVariable int scriptId)
throws Bench4QException, NullPointerException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER, EXCEPTION_HAPPEND
+ "when get behaviors's brief", "/getBehaviorsBrief");
}
ScriptBehaviorsBriefModel result = this
.getTestPlanScriptResultService().getScriptBehaviorsBrief(
testPlanRunID, scriptId);
return result;
}
@RequestMapping(value = "/pagesBrief/{testPlanRunId}/{scriptId}")
@ResponseBody
public ScriptPagesBriefModel getPagesBrief(
@PathVariable UUID testPlanRunId, @PathVariable int scriptId)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER, EXCEPTION_HAPPEND
+ "when get behaviors's brief", "/getBehaviorsBrief");
}
ScriptPagesBriefModel pagesBriefModel = this
.getTestPlanScriptResultService().getScriptPagesBrief(
testPlanRunId, scriptId);
return pagesBriefModel;
}
@RequestMapping(value = "/loadTestPlans", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanResponseModel loadTestPlans() {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildTestPlanResponseModel(false, "no scope", null);
}
List<TestPlan> testPlanDBs = this.testPlanService.loadTestPlans(this
.getPrincipal());
return testPlanDBs == null ? buildTestPlanResponseModel(false,
"exception", null) : buildTestPlanResponseModel(true, null,
testPlanDBs);
}
@RequestMapping(value = "/queryTestPlan/{runId}", method = RequestMethod.GET)
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanDBModel queryTestPlan(@PathVariable UUID runId)
throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER, HAVE_NO_POWER,
"/queryTestPlan/{runId}");
}
return this.getTestPlanService().getTestPlanDBModel(runId);
}
@RequestMapping(value = "/removeTestPlanFromPool", method = {
RequestMethod.GET, RequestMethod.POST })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public TestPlanResponseModel removeTestPlanFromPool(int testPlanId) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return buildTestPlanResponseModel(false, "no scope", null);
}
return buildTestPlanResponseModel(
this.testPlanService.removeTestPlanInDB(testPlanId), null, null);
}
private TestPlanResponseModel buildTestPlanResponseModel(boolean success,
String failCause, List<TestPlan> testPlanDBs) {
TestPlanResponseModel result = new TestPlanResponseModel();
result.setSuccess(success);
result.setFailCause(failCause);
List<TestPlanDBModel> modelList = new ArrayList<TestPlanDBModel>();
if (testPlanDBs != null) {
for (TestPlan testPlanDB : testPlanDBs) {
modelList.add(this.getBusinessMapFactory().toModel(testPlanDB));
}
}
result.setTestPlanDBModels(modelList);
return result;
}
@RequestMapping(value = "/getTestPlanReport", method = { RequestMethod.GET,
RequestMethod.POST })
@ResponseStatus(value = HttpStatus.OK)
@ResponseBody
public void getTestPlanReport(HttpServletResponse response,
@RequestParam UUID testPlanRunID) throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(HAVE_NO_POWER,
"You have no power to get test plan report",
"/getTestPlanReport");
}
buildFileStream(response, testPlanRunID, this.getReportService()
.createReport(testPlanRunID));
}
private void buildFileStream(HttpServletResponse response,
UUID testPlanRunID, byte[] pdfBuffer) {
try {
ServletOutputStream outputStream = response.getOutputStream();
response.reset();
response.setHeader("Content-disposition", "attachment; filename=\""
+ testPlanRunID.toString() + ".pdf\"");
response.addHeader("Content-Length", "" + pdfBuffer.length);
this.logger.info("report of test plan " + testPlanRunID.toString()
+ " length is: " + pdfBuffer.length);
response.setContentType("application/pdf");
outputStream.write(pdfBuffer);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,58 +1,58 @@
package org.bench4q.master.api;
import java.util.UUID;
import org.bench4q.master.domain.service.TestPlanScriptResultService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.share.models.master.ResultLoadModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/testPlanResult")
public class TestPlanResulController extends BaseController {
private TestPlanScriptResultService testPlanScriptResultService;
public TestPlanScriptResultService getTestPlanScriptResultService() {
return testPlanScriptResultService;
}
@Autowired
public void setTestPlanScriptResultService(
TestPlanScriptResultService testPlanScriptResultService) {
this.testPlanScriptResultService = testPlanScriptResultService;
}
@RequestMapping(value = "/{testPlanRunId}/loadScriptBirefResults/{scriptId}/{fieldName}", method = RequestMethod.GET)
@ResponseBody
public ResultLoadModel loadScriptBriefResults(
@PathVariable UUID testPlanRunId, @PathVariable int scriptId,
@PathVariable String fieldName) throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/{testPlanRunId}/script/{scriptId}/{fieldName}");
}
ResultLoadModel ret = new ResultLoadModel();
ret.setValueTimeModels(this.getTestPlanScriptResultService()
.loadScriptBriefSpecificField(testPlanRunId, scriptId,
fieldName));
return ret;
}
@RequestMapping(value = "/{testPlanRunId}/loadBehaviorsBriefResults/{scriptId}/{fieldName}", method = RequestMethod.GET)
@ResponseBody
public ResultLoadModel loadBehaviorsBriefResults(
@PathVariable UUID testPlanRunId, @PathVariable int scriptId,
@PathVariable String fieldName) throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException("400", "not permitted",
"/{testPlanRunId}/loadBehaviorsBriefResults/{scriptId}/{fieldName}");
}
return null;
}
}
package org.bench4q.master.api;
import java.util.UUID;
import org.bench4q.master.domain.service.TestPlanScriptResultService;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.share.models.master.ResultLoadModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/testPlanResult")
public class TestPlanResultController extends BaseController {
private TestPlanScriptResultService testPlanScriptResultService;
public TestPlanScriptResultService getTestPlanScriptResultService() {
return testPlanScriptResultService;
}
@Autowired
public void setTestPlanScriptResultService(
TestPlanScriptResultService testPlanScriptResultService) {
this.testPlanScriptResultService = testPlanScriptResultService;
}
@RequestMapping(value = "/{testPlanRunId}/loadScriptBirefResults/{scriptId}/{fieldName}", method = RequestMethod.GET)
@ResponseBody
public ResultLoadModel loadScriptBriefResults(
@PathVariable UUID testPlanRunId, @PathVariable int scriptId,
@PathVariable String fieldName) throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException(400 + "", "not permitted",
"/{testPlanRunId}/script/{scriptId}/{fieldName}");
}
ResultLoadModel ret = new ResultLoadModel();
ret.setValueTimeModels(this.getTestPlanScriptResultService()
.loadScriptBriefSpecificField(testPlanRunId, scriptId,
fieldName));
return ret;
}
@RequestMapping(value = "/{testPlanRunId}/loadBehaviorsBriefResults/{scriptId}/{fieldName}", method = RequestMethod.GET)
@ResponseBody
public ResultLoadModel loadBehaviorsBriefResults(
@PathVariable UUID testPlanRunId, @PathVariable int scriptId,
@PathVariable String fieldName) throws Bench4QException {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
throw new Bench4QException("400", "not permitted",
"/{testPlanRunId}/loadBehaviorsBriefResults/{scriptId}/{fieldName}");
}
return null;
}
}

View File

@ -1,5 +1,6 @@
package org.bench4q.master.api;
import org.bench4q.master.domain.service.UserService;
import org.bench4q.master.domain.service.auth.AccessToken;
import org.bench4q.master.domain.service.auth.AuthenticationManager;

View File

@ -1,5 +1,5 @@
package org.bench4q.master.domain;
public interface EntityBase {
public Object extractIdentifier();
}
package org.bench4q.master.domain;
public interface EntityBase {
public Object extractIdentifier();
}

View File

@ -1,4 +1,4 @@
package org.bench4q.master.domain;
public interface IAggregate {
}
package org.bench4q.master.domain;
public interface IAggregate {
}

View File

@ -1,28 +1,28 @@
package org.bench4q.master.domain;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.bench4q.master.domain.entity.TestPlanScriptResult;
import org.bench4q.share.models.agent.RunScenarioModel;
public interface RunningScriptInterface {
public int getScriptId();
public UUID getTestPlanID();
public RunScenarioModel getScenario();
public void doAfterDistributeLoad(
List<? extends RunningAgentInterface> agentsAfterDistribute);
public Set<? extends RunningAgentInterface> getRunningAgents();
public int getRequireLoad();
public void doForComplete();
public List<TestPlanScriptResult> doAfterRun();
}
package org.bench4q.master.domain;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import org.bench4q.master.domain.entity.TestPlanScriptResult;
import org.bench4q.share.models.agent.RunScenarioModel;
public interface RunningScriptInterface {
public int getScriptId();
public UUID getTestPlanID();
public RunScenarioModel getScenario();
public void doAfterDistributeLoad(
List<? extends RunningAgentInterface> agentsAfterDistribute);
public Set<? extends RunningAgentInterface> getRunningAgents();
public int getRequireLoad();
public void doForComplete();
public List<TestPlanScriptResult> doAfterRun();
}

View File

@ -1,124 +1,124 @@
package org.bench4q.master.domain.entity;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.factory.TestPlanFactory;
import org.bench4q.master.domain.valueobject.datastatistics.TestMonitorSampler;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.helper.ApplicationContextHelper;
import org.bench4q.share.models.monitor.MonitorMain;
@Entity
@Table(name = "monitor")
public class Monitor {
private int id;
private String hostName;
private int port;
private TestPlan testPlan;
private Set<MonitorResult> results;
private Logger logger = Logger.getLogger(Monitor.class);
private TestPlanFactory testPlanFactory;
public Monitor() {
this.results = new HashSet<MonitorResult>();
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "hostName", nullable = false)
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
@Column(name = "port", nullable = false)
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@ManyToOne
@JoinColumn(name = "testPlanId")
public TestPlan getTestPlan() {
return testPlan;
}
public void setTestPlan(TestPlan testPlan) {
this.testPlan = testPlan;
}
@OneToMany(mappedBy = "monitor", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
public Set<MonitorResult> getResults() {
return results;
}
public void setResults(Set<MonitorResult> results) {
this.results = results;
}
@Transient
public TestMonitorSampler getTestMonitorSampler() {
return ApplicationContextHelper.getContext().getBean(
TestMonitorSampler.class);
}
@Transient
public TestPlanFactory getTestPlanFactory() {
return testPlanFactory;
}
public void setTestPlanFactory(TestPlanFactory testPlanFactory) {
this.testPlanFactory = testPlanFactory;
}
public void doRunInit() {
}
public List<MonitorResult> doAfterRun() {
try {
MonitorMain monitorMain = getTestMonitorSampler().getMonitorResult(
hostName, port);
List<MonitorResult> monitorResults = this.getTestPlanFactory()
.createMonitorResultListWithOutId(monitorMain, testPlan,
this, monitorMain.getSamplingTime());
return monitorResults;
} catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
}
}
package org.bench4q.master.domain.entity;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.factory.TestPlanFactory;
import org.bench4q.master.domain.valueobject.datastatistics.TestMonitorSampler;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.helper.ApplicationContextHelper;
import org.bench4q.share.models.monitor.MonitorMain;
@Entity
@Table(name = "monitor")
public class Monitor {
private int id;
private String hostName;
private int port;
private TestPlan testPlan;
private Set<MonitorResult> results;
private Logger logger = Logger.getLogger(Monitor.class);
private TestPlanFactory testPlanFactory;
public Monitor() {
this.results = new HashSet<MonitorResult>();
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "hostName", nullable = false)
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
@Column(name = "port", nullable = false)
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@ManyToOne
@JoinColumn(name = "testPlanId")
public TestPlan getTestPlan() {
return testPlan;
}
public void setTestPlan(TestPlan testPlan) {
this.testPlan = testPlan;
}
@OneToMany(mappedBy = "monitor", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
public Set<MonitorResult> getResults() {
return results;
}
public void setResults(Set<MonitorResult> results) {
this.results = results;
}
@Transient
public TestMonitorSampler getTestMonitorSampler() {
return ApplicationContextHelper.getContext().getBean(
TestMonitorSampler.class);
}
@Transient
public TestPlanFactory getTestPlanFactory() {
return testPlanFactory;
}
public void setTestPlanFactory(TestPlanFactory testPlanFactory) {
this.testPlanFactory = testPlanFactory;
}
public void doRunInit() {
}
public List<MonitorResult> doAfterRun() {
try {
MonitorMain monitorMain = getTestMonitorSampler().getMonitorResult(
hostName, port);
List<MonitorResult> monitorResults = this.getTestPlanFactory()
.createMonitorResultListWithOutId(monitorMain, testPlan,
this, monitorMain.getSamplingTime());
return monitorResults;
} catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
}
}

View File

@ -1,92 +1,92 @@
package org.bench4q.master.domain.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "MonitorResult")
public class MonitorResult {
private int id;
private TestPlan testPlanDB;
private String type;
private String content;
private String hostNameUnderMonitor;
private Date createDatetime;
private Monitor monitor;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne
@JoinColumn(name = "testPlanRunId", nullable = false)
public TestPlan getTestPlanDB() {
return testPlanDB;
}
public void setTestPlanDB(TestPlan testPlan) {
this.testPlanDB = testPlan;
}
@Column(name = "type", nullable = false)
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Column(name = "content", columnDefinition = "LONGTEXT", nullable = false)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Column(name = "hostNameUnderMonitor", nullable = false)
public String getHostNameUnderMonitor() {
return hostNameUnderMonitor;
}
public void setHostNameUnderMonitor(String hostNameUnderMonitor) {
this.hostNameUnderMonitor = hostNameUnderMonitor;
}
@Column(name = "createDatetime", nullable = false)
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date date) {
this.createDatetime = date;
}
@ManyToOne
@JoinColumn(name = "monitorId")
public Monitor getMonitor() {
return monitor;
}
public void setMonitor(Monitor monitor) {
this.monitor = monitor;
}
}
package org.bench4q.master.domain.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "MonitorResult")
public class MonitorResult {
private int id;
private TestPlan testPlanDB;
private String type;
private String content;
private String hostNameUnderMonitor;
private Date createDatetime;
private Monitor monitor;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne
@JoinColumn(name = "testPlanRunId", nullable = false)
public TestPlan getTestPlanDB() {
return testPlanDB;
}
public void setTestPlanDB(TestPlan testPlan) {
this.testPlanDB = testPlan;
}
@Column(name = "type", nullable = false)
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
@Column(name = "content", columnDefinition = "LONGTEXT", nullable = false)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Column(name = "hostNameUnderMonitor", nullable = false)
public String getHostNameUnderMonitor() {
return hostNameUnderMonitor;
}
public void setHostNameUnderMonitor(String hostNameUnderMonitor) {
this.hostNameUnderMonitor = hostNameUnderMonitor;
}
@Column(name = "createDatetime", nullable = false)
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date date) {
this.createDatetime = date;
}
@ManyToOne
@JoinColumn(name = "monitorId")
public Monitor getMonitor() {
return monitor;
}
public void setMonitor(Monitor monitor) {
this.monitor = monitor;
}
}

View File

@ -1,56 +1,56 @@
package org.bench4q.master.domain.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "planedConfig")
public class PlanedConfig {
private int id;
private long warmUp;
private long executeRange;
private long coolDown;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "warmUp", nullable = false)
public long getWarmUp() {
return warmUp;
}
public void setWarmUp(long warmUp) {
this.warmUp = warmUp;
}
@Column(name = "excuteRange", nullable = false)
public long getExecuteRange() {
return executeRange;
}
public void setExecuteRange(long executeRange) {
this.executeRange = executeRange;
}
@Column(name = "coolDown", nullable = false)
public long getCoolDown() {
return coolDown;
}
public void setCoolDown(long coolDown) {
this.coolDown = coolDown;
}
}
package org.bench4q.master.domain.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "planedConfig")
public class PlanedConfig {
private int id;
private long warmUp;
private long executeRange;
private long coolDown;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "warmUp", nullable = false)
public long getWarmUp() {
return warmUp;
}
public void setWarmUp(long warmUp) {
this.warmUp = warmUp;
}
@Column(name = "excuteRange", nullable = false)
public long getExecuteRange() {
return executeRange;
}
public void setExecuteRange(long executeRange) {
this.executeRange = executeRange;
}
@Column(name = "coolDown", nullable = false)
public long getCoolDown() {
return coolDown;
}
public void setCoolDown(long coolDown) {
this.coolDown = coolDown;
}
}

View File

@ -1,46 +1,46 @@
package org.bench4q.master.domain.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "port")
public class Port {
private int id;
private int port;
private boolean inUse;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "port", nullable = false)
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Column(name = "inUse", nullable = false)
public boolean isInUse() {
return inUse;
}
public void setInUse(boolean inUse) {
this.inUse = inUse;
}
}
package org.bench4q.master.domain.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "port")
public class Port {
private int id;
private int port;
private boolean inUse;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "port", nullable = false)
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Column(name = "inUse", nullable = false)
public boolean isInUse() {
return inUse;
}
public void setInUse(boolean inUse) {
this.inUse = inUse;
}
}

View File

@ -118,7 +118,7 @@ public class Script {
private String buildParamFilesFolder() {
return Main.SCRIPT_PARAM_ROOT_FOLDER + Main.FILE_SEPARATOR
+ this.getId() + Main.FILE_SEPARATOR;
+ this.getName() + Main.FILE_SEPARATOR;
}
public List<File> loadParamFiles() {

View File

@ -1,83 +1,83 @@
package org.bench4q.master.domain.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.xml.bind.JAXBException;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
@Entity
@Table(name = "TestPlanScriptResult")
public class TestPlanScriptResult {
private int id;
private TestPlanScript testPlanScript;
private String resultContent;
private String resultType;
private Date createDatetime;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne
@JoinColumn(name = "testPlanScriptId", nullable = false)
public TestPlanScript getTestPlanScript() {
return testPlanScript;
}
public void setTestPlanScript(TestPlanScript testPlanScript) {
this.testPlanScript = testPlanScript;
}
@Column(name = "resultContent", columnDefinition = "LONGTEXT", nullable = false)
public String getResultContent() {
return resultContent;
}
public void setResultContent(String scriptBriefResultContent) {
this.resultContent = scriptBriefResultContent;
}
@Column(name = "resultType", columnDefinition = "TEXT", nullable = false)
public String getResultType() {
return resultType;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
@Column(name = "createDatetime", nullable = false)
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
public ScriptBriefResultModel extractScriptBriefResultModel() {
try {
return (ScriptBriefResultModel) MarshalHelper.unmarshal(
ScriptBriefResultModel.class, this.getResultContent());
} catch (JAXBException e) {
return null;
}
}
}
package org.bench4q.master.domain.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.xml.bind.JAXBException;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
@Entity
@Table(name = "TestPlanScriptResult")
public class TestPlanScriptResult {
private int id;
private TestPlanScript testPlanScript;
private String resultContent;
private String resultType;
private Date createDatetime;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@ManyToOne
@JoinColumn(name = "testPlanScriptId", nullable = false)
public TestPlanScript getTestPlanScript() {
return testPlanScript;
}
public void setTestPlanScript(TestPlanScript testPlanScript) {
this.testPlanScript = testPlanScript;
}
@Column(name = "resultContent", columnDefinition = "LONGTEXT", nullable = false)
public String getResultContent() {
return resultContent;
}
public void setResultContent(String scriptBriefResultContent) {
this.resultContent = scriptBriefResultContent;
}
@Column(name = "resultType", columnDefinition = "TEXT", nullable = false)
public String getResultType() {
return resultType;
}
public void setResultType(String resultType) {
this.resultType = resultType;
}
@Column(name = "createDatetime", nullable = false)
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
public ScriptBriefResultModel extractScriptBriefResultModel() {
try {
return (ScriptBriefResultModel) MarshalHelper.unmarshal(
ScriptBriefResultModel.class, this.getResultContent());
} catch (JAXBException e) {
return null;
}
}
}

View File

@ -1,91 +1,91 @@
package org.bench4q.master.domain.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
private int id;
private String userName;
private String password;
private byte scope;
// private Set<Script> scripts;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "userName", nullable = false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "scope", nullable = false)
public byte getScope() {
return scope;
}
public void setScope(byte scope) {
this.scope = scope;
}
// @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch =
// FetchType.LAZY)
// @JoinColumn(name = "userId")
// public Set<Script> getScripts() {
// return scripts;
// }
//
// public void setScripts(Set<Script> scripts) {
// this.scripts = scripts;
// }
// public boolean deleteScript(int scriptId) {
// for (Script script : this.getScripts()) {
// if (script.getId() == scriptId) {
// this.getScripts().remove(script);
// return true;
// }
// }
// return false;
// }
//
// public boolean addScript(Script scriptWithoutId) {
// return this.getScripts().add(scriptWithoutId);
// }
//
// public Script getSpecifiedScript(String name) {
// for (Script script : this.getScripts()) {
// if (script.getName().equals(name)) {
// return script;
// }
// }
// return null;
// }
}
package org.bench4q.master.domain.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "user")
public class User {
private int id;
private String userName;
private String password;
private byte scope;
// private Set<Script> scripts;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "userName", nullable = false)
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "password", nullable = false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name = "scope", nullable = false)
public byte getScope() {
return scope;
}
public void setScope(byte scope) {
this.scope = scope;
}
// @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch =
// FetchType.LAZY)
// @JoinColumn(name = "userId")
// public Set<Script> getScripts() {
// return scripts;
// }
//
// public void setScripts(Set<Script> scripts) {
// this.scripts = scripts;
// }
// public boolean deleteScript(int scriptId) {
// for (Script script : this.getScripts()) {
// if (script.getId() == scriptId) {
// this.getScripts().remove(script);
// return true;
// }
// }
// return false;
// }
//
// public boolean addScript(Script scriptWithoutId) {
// return this.getScripts().add(scriptWithoutId);
// }
//
// public Script getSpecifiedScript(String name) {
// for (Script script : this.getScripts()) {
// if (script.getName().equals(name)) {
// return script;
// }
// }
// return null;
// }
}

View File

@ -1,21 +1,21 @@
package org.bench4q.master.domain.entity.plugin;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "fileType")
public class FileType extends ParamType {
private String text;
@Column(name = "text")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
package org.bench4q.master.domain.entity.plugin;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
@Entity
@Table(name = "fileType")
public class FileType extends ParamType {
private String text;
@Column(name = "text")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}

View File

@ -1,32 +1,32 @@
package org.bench4q.master.domain.repository;
import org.apache.log4j.Logger;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
import org.bench4q.master.helper.SessionHelper;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstractRepositoty {
private SessionHelper sessionHelper;
protected Logger logger = Logger.getLogger(AbstractRepositoty.class);
protected SessionHelper getSessionHelper() {
return sessionHelper;
}
@Autowired
protected void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
protected void releaseSession(Session session) {
if (session != null) {
session.close();
}
}
protected abstract void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException;
}
package org.bench4q.master.domain.repository;
import org.apache.log4j.Logger;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
import org.bench4q.master.helper.SessionHelper;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstractRepositoty {
private SessionHelper sessionHelper;
protected Logger logger = Logger.getLogger(AbstractRepositoty.class);
protected SessionHelper getSessionHelper() {
return sessionHelper;
}
@Autowired
protected void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
protected void releaseSession(Session session) {
if (session != null) {
session.close();
}
}
protected abstract void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException;
}

View File

@ -1,13 +1,13 @@
package org.bench4q.master.domain.repository;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
public class MonitorRepository extends AbstractRepositoty {
@Override
protected void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException {
}
}
package org.bench4q.master.domain.repository;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
public class MonitorRepository extends AbstractRepositoty {
@Override
protected void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException {
}
}

View File

@ -1,160 +1,160 @@
package org.bench4q.master.domain.repository;
import java.util.List;
import java.util.Set;
import org.bench4q.master.domain.entity.plugin.BehaviorInfo;
import org.bench4q.master.domain.entity.plugin.PluginInfo;
import org.bench4q.master.domain.entity.plugin.PluginUI;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
@Component
public class PluginRepository extends AbstractRepositoty {
public boolean attatch(PluginUI pluginUI) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
PluginInfo pluginInfo = null;
pluginInfo = (PluginInfo) session
.createCriteria(PluginInfo.class)
.add(Restrictions.eq("name", pluginUI.getPluginInfo()
.getName())).uniqueResult();
if (pluginInfo != null) {
logger.info("the plugin already exists");
return false;
}
session.merge(pluginUI);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
logger.error(ExceptionLog.getStackTrace(e));
return false;
} finally {
releaseSession(session);
}
}
@Override
protected void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException {
if (getPluginUI(value) != null) {
throw new EntityUniqueAlReadyExistException("User with the name "
+ value + "already exists");
}
}
public boolean detach(String pluginName) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
PluginUI pluginUI = getPluginUI(pluginName);
if (pluginUI == null) {
logger.info("plugin not exist");
return false;
}
session.delete(pluginUI);
transaction.commit();
return true;
} catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
transaction.rollback();
return false;
} finally {
releaseSession(session);
}
}
public List<PluginUI> loadPlugins() {
Session session = this.getSessionHelper().openSession();
try {
@SuppressWarnings("unchecked")
List<PluginUI> ret = session.createCriteria(PluginUI.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return ret;
} catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
} finally {
releaseSession(session);
}
}
public Set<BehaviorInfo> loadBehaviorInfos(String pluginName) {
Session session = this.getSessionHelper().openSession();
try {
PluginUI pluginUI = dogetPluginUI(pluginName, session);
Set<BehaviorInfo> behaviorInfos = pluginUI.getBehaviorInfos();
logger.info(behaviorInfos.size());
return behaviorInfos;
} catch (Exception e) {
logger.info(ExceptionLog.getStackTrace(e));
return null;
} finally {
releaseSession(session);
}
}
public boolean isExist(PluginUI plugin) {
Session session = this.getSessionHelper().openSession();
PluginInfo pluginAlreadyExist = (PluginInfo) session
.createCriteria(PluginInfo.class)
.add(Restrictions.eq("name", plugin.getPluginInfo().getName()))
.uniqueResult();
releaseSession(session);
return pluginAlreadyExist != null;
}
public boolean isExist(String pluginName) {
if (getPluginUI(pluginName) == null)
return false;
else {
return true;
}
}
public PluginUI getPluginUI(String pluginName) {
if (pluginName == null) {
logger.info("plugin name is null");
return null;
}
PluginUI pluginUI = null;
Session session = this.getSessionHelper().openSession();
pluginUI = dogetPluginUI(pluginName, session);
releaseSession(session);
if (pluginUI == null)
logger.info(pluginName + " plugin is null from repository");
return pluginUI;
}
public PluginUI dogetPluginUI(String pluginName, Session session) {
PluginInfo pluginInfo = deGetPluginInfo(pluginName, session);
if (pluginInfo == null)
return null;
return (PluginUI) session.createCriteria(PluginUI.class)
.add(Restrictions.eq("pluginInfo", pluginInfo)).uniqueResult();
}
private PluginInfo deGetPluginInfo(String pluginName, Session session) {
return (PluginInfo) session.createCriteria(PluginInfo.class)
.add(Restrictions.eq("name", pluginName)).uniqueResult();
}
public boolean clearPlugins() {
List<PluginUI> pluginUIs = this.loadPlugins();
for (PluginUI pluginUI : pluginUIs) {
if (!this.detach(pluginUI.getPluginInfo().getName()))
return false;
}
return true;
}
}
package org.bench4q.master.domain.repository;
import java.util.List;
import java.util.Set;
import org.bench4q.master.domain.entity.plugin.BehaviorInfo;
import org.bench4q.master.domain.entity.plugin.PluginInfo;
import org.bench4q.master.domain.entity.plugin.PluginUI;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
@Component
public class PluginRepository extends AbstractRepositoty {
public boolean attatch(PluginUI pluginUI) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
PluginInfo pluginInfo = null;
pluginInfo = (PluginInfo) session
.createCriteria(PluginInfo.class)
.add(Restrictions.eq("name", pluginUI.getPluginInfo()
.getName())).uniqueResult();
if (pluginInfo != null) {
logger.info("the plugin already exists");
return false;
}
session.merge(pluginUI);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
logger.error(ExceptionLog.getStackTrace(e));
return false;
} finally {
releaseSession(session);
}
}
@Override
protected void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException {
if (getPluginUI(value) != null) {
throw new EntityUniqueAlReadyExistException("User with the name "
+ value + "already exists");
}
}
public boolean detach(String pluginName) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
PluginUI pluginUI = getPluginUI(pluginName);
if (pluginUI == null) {
logger.info("plugin not exist");
return false;
}
session.delete(pluginUI);
transaction.commit();
return true;
} catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
transaction.rollback();
return false;
} finally {
releaseSession(session);
}
}
public List<PluginUI> loadPlugins() {
Session session = this.getSessionHelper().openSession();
try {
@SuppressWarnings("unchecked")
List<PluginUI> ret = session.createCriteria(PluginUI.class)
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
return ret;
} catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
} finally {
releaseSession(session);
}
}
public Set<BehaviorInfo> loadBehaviorInfos(String pluginName) {
Session session = this.getSessionHelper().openSession();
try {
PluginUI pluginUI = dogetPluginUI(pluginName, session);
Set<BehaviorInfo> behaviorInfos = pluginUI.getBehaviorInfos();
logger.info(behaviorInfos.size());
return behaviorInfos;
} catch (Exception e) {
logger.info(ExceptionLog.getStackTrace(e));
return null;
} finally {
releaseSession(session);
}
}
public boolean isExist(PluginUI plugin) {
Session session = this.getSessionHelper().openSession();
PluginInfo pluginAlreadyExist = (PluginInfo) session
.createCriteria(PluginInfo.class)
.add(Restrictions.eq("name", plugin.getPluginInfo().getName()))
.uniqueResult();
releaseSession(session);
return pluginAlreadyExist != null;
}
public boolean isExist(String pluginName) {
if (getPluginUI(pluginName) == null)
return false;
else {
return true;
}
}
public PluginUI getPluginUI(String pluginName) {
if (pluginName == null) {
logger.info("plugin name is null");
return null;
}
PluginUI pluginUI = null;
Session session = this.getSessionHelper().openSession();
pluginUI = dogetPluginUI(pluginName, session);
releaseSession(session);
if (pluginUI == null)
logger.info(pluginName + " plugin is null from repository");
return pluginUI;
}
public PluginUI dogetPluginUI(String pluginName, Session session) {
PluginInfo pluginInfo = deGetPluginInfo(pluginName, session);
if (pluginInfo == null)
return null;
return (PluginUI) session.createCriteria(PluginUI.class)
.add(Restrictions.eq("pluginInfo", pluginInfo)).uniqueResult();
}
private PluginInfo deGetPluginInfo(String pluginName, Session session) {
return (PluginInfo) session.createCriteria(PluginInfo.class)
.add(Restrictions.eq("name", pluginName)).uniqueResult();
}
public boolean clearPlugins() {
List<PluginUI> pluginUIs = this.loadPlugins();
for (PluginUI pluginUI : pluginUIs) {
if (!this.detach(pluginUI.getPluginInfo().getName()))
return false;
}
return true;
}
}

View File

@ -1,123 +1,123 @@
package org.bench4q.master.domain.repository;
import java.util.LinkedList;
import java.util.List;
import org.bench4q.master.domain.entity.Script;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
@Component
public class ScriptRepositoty extends AbstractRepositoty {
public boolean attach(Script scriptWithoutId) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
session.merge(scriptWithoutId);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
logger.error(ExceptionLog.getStackTrace(e));
return false;
} finally {
releaseSession(session);
}
}
@Override
protected void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException {
if (getScriptByName(value) != null) {
throw new EntityUniqueAlReadyExistException("Script with the name "
+ value + " already exists");
}
}
public boolean detach(int id) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Script script = (Script) session.get(Script.class, id);
if (script == null) {
return false;
}
session.delete(script);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
logger.error(ExceptionLog.getStackTrace(e));
return false;
} finally {
releaseSession(session);
}
}
public boolean update(Script script) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
session.update(script);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
return false;
} finally {
releaseSession(session);
}
}
public Script getEntity(int id) {
Session session = this.getSessionHelper().openSession();
Script result = (Script) session.get(Script.class, id);
releaseSession(session);
return result;
}
public Script getScriptByName(String name) {
Session session = this.getSessionHelper().openSession();
try {
return (Script) session.createCriteria(Script.class)
.add(Restrictions.eq("name", name)).uniqueResult();
} catch (Exception e) {
logger.info(ExceptionLog.getStackTrace(e));
return null;
} finally {
releaseSession(session);
}
}
@SuppressWarnings("unchecked")
public List<Script> getWith(Criterion criterion, User user) {
Session session = this.getSessionHelper().openSession();
try {
return session.createCriteria(Script.class)
.add(Restrictions.eq("user", user)).add(criterion).list();
} catch (Exception e) {
return new LinkedList<Script>();
} finally {
releaseSession(session);
}
}
public List<Script> loadEntities(User user) {
Session session = this.getSessionHelper().openSession();
@SuppressWarnings("unchecked")
List<Script> scripts = session.createCriteria(Script.class)
.add(Restrictions.eq("user", user)).list();
releaseSession(session);
return scripts;
}
}
package org.bench4q.master.domain.repository;
import java.util.LinkedList;
import java.util.List;
import org.bench4q.master.domain.entity.Script;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
@Component
public class ScriptRepositoty extends AbstractRepositoty {
public boolean attach(Script scriptWithoutId) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
session.merge(scriptWithoutId);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
logger.error(ExceptionLog.getStackTrace(e));
return false;
} finally {
releaseSession(session);
}
}
@Override
protected void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException {
if (getScriptByName(value) != null) {
throw new EntityUniqueAlReadyExistException("Script with the name "
+ value + " already exists");
}
}
public boolean detach(int id) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Script script = (Script) session.get(Script.class, id);
if (script == null) {
return false;
}
session.delete(script);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
logger.error(ExceptionLog.getStackTrace(e));
return false;
} finally {
releaseSession(session);
}
}
public boolean update(Script script) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
session.update(script);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
return false;
} finally {
releaseSession(session);
}
}
public Script getEntity(int id) {
Session session = this.getSessionHelper().openSession();
Script result = (Script) session.get(Script.class, id);
releaseSession(session);
return result;
}
public Script getScriptByName(String name) {
Session session = this.getSessionHelper().openSession();
try {
return (Script) session.createCriteria(Script.class)
.add(Restrictions.eq("name", name)).uniqueResult();
} catch (Exception e) {
logger.info(ExceptionLog.getStackTrace(e));
return null;
} finally {
releaseSession(session);
}
}
@SuppressWarnings("unchecked")
public List<Script> getWith(Criterion criterion, User user) {
Session session = this.getSessionHelper().openSession();
try {
return session.createCriteria(Script.class)
.add(Restrictions.eq("user", user)).add(criterion).list();
} catch (Exception e) {
return new LinkedList<Script>();
} finally {
releaseSession(session);
}
}
public List<Script> loadEntities(User user) {
Session session = this.getSessionHelper().openSession();
@SuppressWarnings("unchecked")
List<Script> scripts = session.createCriteria(Script.class)
.add(Restrictions.eq("user", user)).list();
releaseSession(session);
return scripts;
}
}

View File

@ -1,119 +1,119 @@
package org.bench4q.master.domain.repository;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
@Component
public class UserRepository extends AbstractRepositoty {
public boolean attatch(User user) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
User userAlreadyExist = null;
try {
userAlreadyExist = (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", user.getUserName()))
.uniqueResult();
if (userAlreadyExist != null) {
return false;
}
session.merge(user);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
return false;
} finally {
releaseSession(session);
}
}
@Override
protected void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException {
if (getUser(value) != null) {
throw new EntityUniqueAlReadyExistException("User with the name "
+ value + "already exists");
}
}
public boolean detach(String userName) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
User userAlreadyExist = (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", userName)).uniqueResult();
if (userAlreadyExist == null) {
return false;
}
session.delete(userAlreadyExist);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
return false;
} finally {
releaseSession(session);
}
}
public boolean updateEntity(User user) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
session.update(user);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
logger.error(ExceptionLog.getStackTrace(e));
return false;
} finally {
releaseSession(session);
}
}
public boolean isExist(User user) {
Session session = this.getSessionHelper().openSession();
User userAlreadyExist = (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", user.getUserName()))
.add(Restrictions.eq("password", user.getPassword()))
.uniqueResult();
releaseSession(session);
return userAlreadyExist != null;
}
public User getEntity(int id) {
User result = null;
Session session = this.getSessionHelper().openSession();
result = (User) session.get(User.class, id);
releaseSession(session);
return result;
}
public User getUser(String userName) {
User result = null;
Session session = this.getSessionHelper().openSession();
result = doGetUser(userName, session);
releaseSession(session);
return result;
}
private User doGetUser(String userName, Session session) {
return (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", userName)).uniqueResult();
}
// public Set<Script> loadScripts(String userName) {
// Session session = this.getSessionHelper().openSession();
// User user = doGetUser(userName, session);
// Set<Script> result = user.getScripts();
// return result;
// }
}
package org.bench4q.master.domain.repository;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.exception.ExceptionUtils.EntityUniqueAlReadyExistException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Component;
@Component
public class UserRepository extends AbstractRepositoty {
public boolean attatch(User user) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
User userAlreadyExist = null;
try {
userAlreadyExist = (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", user.getUserName()))
.uniqueResult();
if (userAlreadyExist != null) {
return false;
}
session.merge(user);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
return false;
} finally {
releaseSession(session);
}
}
@Override
protected void guardOtherUniqueConditionForEntity(
String uniquePropertyName, String value)
throws EntityUniqueAlReadyExistException {
if (getUser(value) != null) {
throw new EntityUniqueAlReadyExistException("User with the name "
+ value + "already exists");
}
}
public boolean detach(String userName) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
User userAlreadyExist = (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", userName)).uniqueResult();
if (userAlreadyExist == null) {
return false;
}
session.delete(userAlreadyExist);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
return false;
} finally {
releaseSession(session);
}
}
public boolean updateEntity(User user) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
session.update(user);
transaction.commit();
return true;
} catch (Exception e) {
transaction.rollback();
logger.error(ExceptionLog.getStackTrace(e));
return false;
} finally {
releaseSession(session);
}
}
public boolean isExist(User user) {
Session session = this.getSessionHelper().openSession();
User userAlreadyExist = (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", user.getUserName()))
.add(Restrictions.eq("password", user.getPassword()))
.uniqueResult();
releaseSession(session);
return userAlreadyExist != null;
}
public User getEntity(int id) {
User result = null;
Session session = this.getSessionHelper().openSession();
result = (User) session.get(User.class, id);
releaseSession(session);
return result;
}
public User getUser(String userName) {
User result = null;
Session session = this.getSessionHelper().openSession();
result = doGetUser(userName, session);
releaseSession(session);
return result;
}
private User doGetUser(String userName, Session session) {
return (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", userName)).uniqueResult();
}
// public Set<Script> loadScripts(String userName) {
// Session session = this.getSessionHelper().openSession();
// User user = doGetUser(userName, session);
// Set<Script> result = user.getScripts();
// return result;
// }
}

View File

@ -1,99 +1,99 @@
package org.bench4q.master.domain.service;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.bench4q.master.domain.repository.PluginRepository;
import org.bench4q.master.domain.entity.plugin.BehaviorInfo;
import org.bench4q.master.domain.entity.plugin.PluginUI;
import org.bench4q.master.domain.factory.PluginDomainFactory;
import org.bench4q.master.domain.factory.PluginEntityFactory;
import org.bench4q.share.models.master.plugin.BehaviorInfoModel;
import org.bench4q.share.models.master.plugin.PluginUIModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PluginService {
private PluginRepository pluginRepository;
private PluginEntityFactory pluginEntityFactory;
private PluginDomainFactory pluginDomainFactory;
public PluginRepository getPluginRepository() {
return pluginRepository;
}
@Autowired
private void setPluginRepository(PluginRepository pluginRepository) {
this.pluginRepository = pluginRepository;
}
public PluginEntityFactory getPluginEntityFactory() {
return pluginEntityFactory;
}
@Autowired
private void setPluginEntityFactory(PluginEntityFactory pluginEntityFactory) {
this.pluginEntityFactory = pluginEntityFactory;
}
public PluginDomainFactory getPluginDomainFactory() {
return pluginDomainFactory;
}
@Autowired
public void setPluginDomainFactory(PluginDomainFactory pluginDomainFactory) {
this.pluginDomainFactory = pluginDomainFactory;
}
public boolean addPlugin(String pluginUIContent) {
return this.getPluginRepository().attatch(
this.getPluginEntityFactory().createPluginUIWithOutId(
pluginUIContent));
}
public boolean deletePlugin(String pluginName) {
return this.getPluginRepository().detach(pluginName);
}
public List<String> getPluginNameList() {
List<PluginUIModel> pluginUIModels = this.loadPluginUIs();
if (pluginUIModels == null)
return null;
List<String> pluginNameList = new LinkedList<String>();
for (PluginUIModel pluginUIModel : this.loadPluginUIs()) {
pluginNameList.add(pluginUIModel.getPluginInfoModel().getName());
}
return pluginNameList;
}
public List<PluginUIModel> loadPluginUIs() {
List<PluginUI> pluginUIs = this.getPluginRepository().loadPlugins();
if (pluginUIs == null)
return null;
List<PluginUIModel> pluginUIModels = new LinkedList<PluginUIModel>();
for (PluginUI pluginUI : pluginUIs) {
pluginUIModels.add(this.getPluginDomainFactory()
.createPluginUIModelwithOutBehaviors(pluginUI));
}
return pluginUIModels;
}
public List<BehaviorInfoModel> loadBehaviorInfoModels(String pluginName) {
Set<BehaviorInfo> behaviorInfos = this.getPluginRepository()
.loadBehaviorInfos(pluginName);
if (behaviorInfos == null)
return null;
return this.getPluginDomainFactory().createBehaviorInfoModels(
this.getPluginRepository().loadBehaviorInfos(pluginName));
}
public boolean isPluginExist(String pluginName) {
return this.getPluginRepository().isExist(pluginName);
}
}
package org.bench4q.master.domain.service;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import org.bench4q.master.domain.repository.PluginRepository;
import org.bench4q.master.domain.entity.plugin.BehaviorInfo;
import org.bench4q.master.domain.entity.plugin.PluginUI;
import org.bench4q.master.domain.factory.PluginDomainFactory;
import org.bench4q.master.domain.factory.PluginEntityFactory;
import org.bench4q.share.models.master.plugin.BehaviorInfoModel;
import org.bench4q.share.models.master.plugin.PluginUIModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PluginService {
private PluginRepository pluginRepository;
private PluginEntityFactory pluginEntityFactory;
private PluginDomainFactory pluginDomainFactory;
public PluginRepository getPluginRepository() {
return pluginRepository;
}
@Autowired
private void setPluginRepository(PluginRepository pluginRepository) {
this.pluginRepository = pluginRepository;
}
public PluginEntityFactory getPluginEntityFactory() {
return pluginEntityFactory;
}
@Autowired
private void setPluginEntityFactory(PluginEntityFactory pluginEntityFactory) {
this.pluginEntityFactory = pluginEntityFactory;
}
public PluginDomainFactory getPluginDomainFactory() {
return pluginDomainFactory;
}
@Autowired
public void setPluginDomainFactory(PluginDomainFactory pluginDomainFactory) {
this.pluginDomainFactory = pluginDomainFactory;
}
public boolean addPlugin(String pluginUIContent) {
return this.getPluginRepository().attatch(
this.getPluginEntityFactory().createPluginUIWithOutId(
pluginUIContent));
}
public boolean deletePlugin(String pluginName) {
return this.getPluginRepository().detach(pluginName);
}
public List<String> getPluginNameList() {
List<PluginUIModel> pluginUIModels = this.loadPluginUIs();
if (pluginUIModels == null)
return null;
List<String> pluginNameList = new LinkedList<String>();
for (PluginUIModel pluginUIModel : this.loadPluginUIs()) {
pluginNameList.add(pluginUIModel.getPluginInfoModel().getName());
}
return pluginNameList;
}
public List<PluginUIModel> loadPluginUIs() {
List<PluginUI> pluginUIs = this.getPluginRepository().loadPlugins();
if (pluginUIs == null)
return null;
List<PluginUIModel> pluginUIModels = new LinkedList<PluginUIModel>();
for (PluginUI pluginUI : pluginUIs) {
pluginUIModels.add(this.getPluginDomainFactory()
.createPluginUIModelwithOutBehaviors(pluginUI));
}
return pluginUIModels;
}
public List<BehaviorInfoModel> loadBehaviorInfoModels(String pluginName) {
Set<BehaviorInfo> behaviorInfos = this.getPluginRepository()
.loadBehaviorInfos(pluginName);
if (behaviorInfos == null)
return null;
return this.getPluginDomainFactory().createBehaviorInfoModels(
this.getPluginRepository().loadBehaviorInfos(pluginName));
}
public boolean isPluginExist(String pluginName) {
return this.getPluginRepository().isExist(pluginName);
}
}

View File

@ -1,171 +1,171 @@
package org.bench4q.master.domain.service;
import java.util.List;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.Port;
import org.bench4q.master.helper.SessionHelper;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PortPoolService {
private SessionHelper sessionHelper = new SessionHelper();
private Logger logger = Logger.getLogger(PortPoolService.class);
public SessionHelper getSessionHelper() {
return sessionHelper;
}
@Autowired
public void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
public boolean addPortToDBPool(int port) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Port portDB = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("port", port)).uniqueResult();
if (portDB != null) {
return false;
}
portDB = new Port();
portDB.setPort(port);
session.merge(portDB);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean removePortFromDBPool(int id) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Port portDB = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("id", id)).uniqueResult();
if (portDB == null) {
this.logger
.error("Port to delete don't exist where the portId is "
+ id);
return false;
}
session.delete(portDB);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
@SuppressWarnings("unchecked")
public Port getAPortNotInUse() {
// If i do the HA in the pool, shall i lock this change for this port
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
Port port = null;
try {
List<Port> portList = (List<Port>) session
.createCriteria(Port.class)
.add(Restrictions.eq("inUse", false)).list();
if (portList.isEmpty()) {
return null;
}
port = portList.get(0);
port.setInUse(true);
transaction.commit();
return port;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean backPort(int port) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
System.out.println("back the port " + port + " to DB!");
Port portEntity = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("port", port)).uniqueResult();
if (portEntity == null || !portEntity.isInUse()) {
return false;
}
portEntity.setInUse(false);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
@SuppressWarnings("unchecked")
public List<Port> loadPortList() {
Session session = this.getSessionHelper().openSession();
try {
List<Port> ports = session.createCriteria(Port.class).list();
return ports;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean editPort(Port portInParam) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Port portInDB = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("port", portInParam.getPort()))
.uniqueResult();
portInDB.setInUse(portInParam.isInUse());
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
}
package org.bench4q.master.domain.service;
import java.util.List;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.Port;
import org.bench4q.master.helper.SessionHelper;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class PortPoolService {
private SessionHelper sessionHelper = new SessionHelper();
private Logger logger = Logger.getLogger(PortPoolService.class);
public SessionHelper getSessionHelper() {
return sessionHelper;
}
@Autowired
public void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
public boolean addPortToDBPool(int port) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Port portDB = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("port", port)).uniqueResult();
if (portDB != null) {
return false;
}
portDB = new Port();
portDB.setPort(port);
session.merge(portDB);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean removePortFromDBPool(int id) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Port portDB = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("id", id)).uniqueResult();
if (portDB == null) {
this.logger
.error("Port to delete don't exist where the portId is "
+ id);
return false;
}
session.delete(portDB);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
@SuppressWarnings("unchecked")
public Port getAPortNotInUse() {
// If i do the HA in the pool, shall i lock this change for this port
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
Port port = null;
try {
List<Port> portList = (List<Port>) session
.createCriteria(Port.class)
.add(Restrictions.eq("inUse", false)).list();
if (portList.isEmpty()) {
return null;
}
port = portList.get(0);
port.setInUse(true);
transaction.commit();
return port;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean backPort(int port) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
System.out.println("back the port " + port + " to DB!");
Port portEntity = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("port", port)).uniqueResult();
if (portEntity == null || !portEntity.isInUse()) {
return false;
}
portEntity.setInUse(false);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
@SuppressWarnings("unchecked")
public List<Port> loadPortList() {
Session session = this.getSessionHelper().openSession();
try {
List<Port> ports = session.createCriteria(Port.class).list();
return ports;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean editPort(Port portInParam) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Port portInDB = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("port", portInParam.getPort()))
.uniqueResult();
portInDB.setInUse(portInParam.isInUse());
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
}

View File

@ -1,115 +1,115 @@
package org.bench4q.master.domain.service;
import java.util.Date;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.Script;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.domain.repository.ScriptRepositoty;
import org.bench4q.master.domain.repository.UserRepository;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.agent.RunScenarioModel;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component
public class ScriptService {
private ScriptRepositoty scriptRepositoty;
private UserRepository userRepository;
private Logger logger = Logger.getLogger(ScriptService.class);
private ScriptRepositoty getScriptRepositoty() {
return scriptRepositoty;
}
@Autowired
private void setScriptRepositoty(ScriptRepositoty scriptRepositoty) {
this.scriptRepositoty = scriptRepositoty;
}
private UserRepository getUserRepository() {
return userRepository;
}
@Autowired
private void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
*
* @param scriptName
* @param userId
* @param scriptContent
* @param paramFiles
* , this param may be null, and is permitted so.
* @return
*/
public boolean saveScript(String scriptName, int userId,
String scriptContent, List<MultipartFile> paramFiles) {
return this.getScriptRepositoty().attach(
Script.createScriptWithoutId(scriptName, scriptContent, this
.getUserRepository().getEntity(userId), paramFiles));
}
public Script getScript(int scriptId) {
return this.getScriptRepositoty().getEntity(scriptId);
}
public Script getScriptByName(String name) {
return this.getScriptRepositoty().getScriptByName(name);
}
public List<Script> loadScripts(User user) {
return this.getScriptRepositoty().loadEntities(user);
}
public List<Script> queryScriptsByCreateTime(Date startDate, Date endDate,
User user) {
return this.getScriptRepositoty().getWith(
Restrictions.between("createDateTime", startDate, endDate),
user);
}
public RunScenarioModel getRunSceniroModelByScriptId(int scriptId) {
String content = this.getScriptRepositoty().getEntity(scriptId)
.getScriptContent();
if (content == null) {
return null;
}
try {
return (RunScenarioModel) MarshalHelper.unmarshal(
RunScenarioModel.class, content);
} catch (JAXBException e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
}
public boolean deleteScript(int id, int userId) {
try {
Script script = this.getScriptRepositoty().getEntity(id);
if (script == null || script.getUser().getId() != userId) {
return false;
}
return this.getScriptRepositoty().detach(id);
} catch (Exception e) {
return false;
}
}
public boolean alterScriptContent(int id, int ownerId, String content) {
Script script = this.getScriptRepositoty().getEntity(id);
if (script.getUser().getId() != ownerId) {
return false;
}
script.setScriptContent(content);
return this.getScriptRepositoty().update(script);
}
}
package org.bench4q.master.domain.service;
import java.util.Date;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.Script;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.domain.repository.ScriptRepositoty;
import org.bench4q.master.domain.repository.UserRepository;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.agent.RunScenarioModel;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
@Component
public class ScriptService {
private ScriptRepositoty scriptRepositoty;
private UserRepository userRepository;
private Logger logger = Logger.getLogger(ScriptService.class);
private ScriptRepositoty getScriptRepositoty() {
return scriptRepositoty;
}
@Autowired
private void setScriptRepositoty(ScriptRepositoty scriptRepositoty) {
this.scriptRepositoty = scriptRepositoty;
}
private UserRepository getUserRepository() {
return userRepository;
}
@Autowired
private void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
*
* @param scriptName
* @param userId
* @param scriptContent
* @param paramFiles
* , this param may be null, and is permitted so.
* @return
*/
public boolean saveScript(String scriptName, int userId,
String scriptContent, List<MultipartFile> paramFiles) {
return this.getScriptRepositoty().attach(
Script.createScriptWithoutId(scriptName, scriptContent, this
.getUserRepository().getEntity(userId), paramFiles));
}
public Script getScript(int scriptId) {
return this.getScriptRepositoty().getEntity(scriptId);
}
public Script getScriptByName(String name) {
return this.getScriptRepositoty().getScriptByName(name);
}
public List<Script> loadScripts(User user) {
return this.getScriptRepositoty().loadEntities(user);
}
public List<Script> queryScriptsByCreateTime(Date startDate, Date endDate,
User user) {
return this.getScriptRepositoty().getWith(
Restrictions.between("createDateTime", startDate, endDate),
user);
}
public RunScenarioModel getRunSceniroModelByScriptId(int scriptId) {
String content = this.getScriptRepositoty().getEntity(scriptId)
.getScriptContent();
if (content == null) {
return null;
}
try {
return (RunScenarioModel) MarshalHelper.unmarshal(
RunScenarioModel.class, content);
} catch (JAXBException e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
}
public boolean deleteScript(int id, int userId) {
try {
Script script = this.getScriptRepositoty().getEntity(id);
if (script == null || script.getUser().getId() != userId) {
return false;
}
return this.getScriptRepositoty().detach(id);
} catch (Exception e) {
return false;
}
}
public boolean alterScriptContent(int id, int ownerId, String content) {
Script script = this.getScriptRepositoty().getEntity(id);
if (script.getUser().getId() != ownerId) {
return false;
}
script.setScriptContent(content);
return this.getScriptRepositoty().update(script);
}
}

View File

@ -1,109 +1,109 @@
package org.bench4q.master.domain.service;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.Monitor;
import org.bench4q.master.domain.entity.MonitorResult;
import org.bench4q.master.domain.entity.TestPlan;
import org.bench4q.master.domain.entity.TestPlanScript;
import org.bench4q.master.domain.entity.TestPlanScriptResult;
import org.bench4q.master.domain.repository.TestPlanRepository;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.helper.SessionHelper;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TestResultSave{
private SessionHelper sessionHelper;
private TestPlanRepository testPlanRepository;
private Logger logger = Logger.getLogger(TestResultSave.class);
public TestResultSave() {
}
private TestPlanRepository getTestPlanRepository() {
return testPlanRepository;
}
@Autowired
private void setTestPlanRepository(TestPlanRepository testPlanRepository) {
this.testPlanRepository = testPlanRepository;
}
private SessionHelper getSessionHelper() {
return sessionHelper;
}
@Autowired
private void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
public void update(TestPlan testPlan, List<Object> messages) {
Session session = this.getSessionHelper().openSession();
TestPlan testPlanFromRepo = this.getTestPlanRepository()
.doGetTestPlanBy(session,
UUID.fromString(testPlan.getTestPlanRunId()));
updateTestPlanResult(messages, testPlanFromRepo);
saveUpdatedResult(testPlanFromRepo, session);
session.close();
}
private void updateTestPlanResult(List<Object> messages,
TestPlan testPlanFromRepo) {
for (Object message : messages) {
if(message==null)
return;
if (message instanceof MonitorResult) {
updateTestplanMonitorResult((MonitorResult) message,
testPlanFromRepo);
}
else if(message instanceof TestPlanScriptResult){
updateTestPlanScriptResult((TestPlanScriptResult)message, testPlanFromRepo);
}
}
}
private void updateTestPlanScriptResult(TestPlanScriptResult message,
TestPlan testPlanFromRepo) {
try {
TestPlanScript testPlanScriptFromRepo = testPlanFromRepo
.extracSpecifiedScript(message.getTestPlanScript().getScriptId());
testPlanScriptFromRepo.getTestPlanScriptResults().add(message);
} catch (Exception e) {
logger.info(ExceptionLog.getStackTrace(e));
}
}
private void updateTestplanMonitorResult(MonitorResult monitorResult,
TestPlan testPlanFromRepo) {
try {
Monitor monitorFromRepo = testPlanFromRepo
.extractSpecifiedMonitor(monitorResult.getMonitor()
.getHostName());
monitorFromRepo.getResults().add(monitorResult);
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean saveUpdatedResult(TestPlan testPlan, Session session) {
try {
getTestPlanRepository().doUpdateEntity(session, testPlan);
return true;
} catch (Exception e) {
logger.info(ExceptionLog.getStackTrace(e));
return false;
}
}
}
package org.bench4q.master.domain.service;
import java.util.List;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.entity.Monitor;
import org.bench4q.master.domain.entity.MonitorResult;
import org.bench4q.master.domain.entity.TestPlan;
import org.bench4q.master.domain.entity.TestPlanScript;
import org.bench4q.master.domain.entity.TestPlanScriptResult;
import org.bench4q.master.domain.repository.TestPlanRepository;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.master.helper.SessionHelper;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TestResultSave{
private SessionHelper sessionHelper;
private TestPlanRepository testPlanRepository;
private Logger logger = Logger.getLogger(TestResultSave.class);
public TestResultSave() {
}
private TestPlanRepository getTestPlanRepository() {
return testPlanRepository;
}
@Autowired
private void setTestPlanRepository(TestPlanRepository testPlanRepository) {
this.testPlanRepository = testPlanRepository;
}
private SessionHelper getSessionHelper() {
return sessionHelper;
}
@Autowired
private void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
public void update(TestPlan testPlan, List<Object> messages) {
Session session = this.getSessionHelper().openSession();
TestPlan testPlanFromRepo = this.getTestPlanRepository()
.doGetTestPlanBy(session,
UUID.fromString(testPlan.getTestPlanRunId()));
updateTestPlanResult(messages, testPlanFromRepo);
saveUpdatedResult(testPlanFromRepo, session);
session.close();
}
private void updateTestPlanResult(List<Object> messages,
TestPlan testPlanFromRepo) {
for (Object message : messages) {
if(message==null)
return;
if (message instanceof MonitorResult) {
updateTestplanMonitorResult((MonitorResult) message,
testPlanFromRepo);
}
else if(message instanceof TestPlanScriptResult){
updateTestPlanScriptResult((TestPlanScriptResult)message, testPlanFromRepo);
}
}
}
private void updateTestPlanScriptResult(TestPlanScriptResult message,
TestPlan testPlanFromRepo) {
try {
TestPlanScript testPlanScriptFromRepo = testPlanFromRepo
.extracSpecifiedScript(message.getTestPlanScript().getScriptId());
testPlanScriptFromRepo.getTestPlanScriptResults().add(message);
} catch (Exception e) {
logger.info(ExceptionLog.getStackTrace(e));
}
}
private void updateTestplanMonitorResult(MonitorResult monitorResult,
TestPlan testPlanFromRepo) {
try {
Monitor monitorFromRepo = testPlanFromRepo
.extractSpecifiedMonitor(monitorResult.getMonitor()
.getHostName());
monitorFromRepo.getResults().add(monitorResult);
} catch (Exception e) {
e.printStackTrace();
}
}
private boolean saveUpdatedResult(TestPlan testPlan, Session session) {
try {
getTestPlanRepository().doUpdateEntity(session, testPlan);
return true;
} catch (Exception e) {
logger.info(ExceptionLog.getStackTrace(e));
return false;
}
}
}

View File

@ -1,55 +1,55 @@
package org.bench4q.master.domain.service.auth;
import java.io.Serializable;
import java.util.Date;
public class AccessToken implements Serializable {
private static final long serialVersionUID = 4134631390384650898L;
private String userName;
private String password;
private byte scope;
private Date generateTime;
private int expiresIn;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getGenerateTime() {
return generateTime;
}
public void setGenerateTime(Date generateTime) {
this.generateTime = generateTime;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public byte getScope() {
return scope;
}
public void setScope(byte scope) {
this.scope = scope;
}
}
package org.bench4q.master.domain.service.auth;
import java.io.Serializable;
import java.util.Date;
public class AccessToken implements Serializable {
private static final long serialVersionUID = 4134631390384650898L;
private String userName;
private String password;
private byte scope;
private Date generateTime;
private int expiresIn;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getGenerateTime() {
return generateTime;
}
public void setGenerateTime(Date generateTime) {
this.generateTime = generateTime;
}
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
public byte getScope() {
return scope;
}
public void setScope(byte scope) {
this.scope = scope;
}
}

View File

@ -1,150 +1,150 @@
package org.bench4q.master.domain.service.auth;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.domain.repository.UserRepository;
import org.bench4q.master.helper.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AuthenticationManager {
private final int defaultExpiresTime = 3600;
private CryptoManager cryptoManager;
private UserRepository userRepository;
private StringHelper stringHelper;
private CryptoManager getCryptoManager() {
return cryptoManager;
}
@Autowired
private void setCryptoManager(CryptoManager cryptoManager) {
this.cryptoManager = cryptoManager;
}
private StringHelper getStringHelper() {
return stringHelper;
}
@Autowired
private void setStringHelper(StringHelper stringHelper) {
this.stringHelper = stringHelper;
}
private UserRepository getUserRepository() {
return userRepository;
}
@Autowired
private void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getPrincipal(HttpServletRequest request) {
AccessToken accessToken = this.getAccessToken(request);
if (accessToken == null) {
return null;
}
return this.extractUser(accessToken);
}
public boolean checkScope(HttpServletRequest request, byte requiredScope) {
AccessToken accessToken = this.getAccessToken(request);
if (accessToken == null) {
return false;
}
return isScopeMeet(accessToken.getScope(), requiredScope);
}
public boolean isScopeMeet(byte actualScope, byte requiredScope) {
return actualScope >= requiredScope;
}
private String generateCredential(User user) {
AccessToken accessToken = this.generateAccessToken(user);
return this.generateCredentialFromAccessToken(accessToken);
}
public String generateCredential(String userName) {
return this.generateCredential(this.getUserRepository().getUser(
userName));
}
private AccessToken getAccessToken(HttpServletRequest request) {
if (request.getHeader("Authorization") == null) {
return null;
}
if (!request.getHeader("Authorization").startsWith("Bearer ")) {
return null;
}
String hex = request.getHeader("Authorization").substring(
"Bearer ".length());
byte[] bytes = this.getStringHelper().convertToBytes(hex);
return this.extractAccessToken(bytes);
}
private User extractUser(AccessToken accessToken) {
if (accessToken == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(accessToken.getGenerateTime());
calendar.add(Calendar.SECOND, accessToken.getExpiresIn());
Date expireTime = calendar.getTime();
if (expireTime.before(new Date(System.currentTimeMillis()))) {
return null;
}
return this.getUserRepository().getUser(accessToken.getUserName());
}
private AccessToken generateAccessToken(User user) {
AccessToken accessToken = new AccessToken();
accessToken.setExpiresIn(this.defaultExpiresTime);
accessToken.setGenerateTime(new Date(System.currentTimeMillis()));
accessToken.setPassword(user.getPassword());
accessToken.setUserName(user.getUserName());
accessToken.setScope(user.getScope());
return accessToken;
}
public AccessToken generateAccessToken(String userName) {
return this.generateAccessToken(this.getUserRepository().getUser(
userName));
}
private AccessToken extractAccessToken(byte[] bytes) {
try {
byte[] decrypted = this.getCryptoManager().decrypt(bytes);
ObjectInputStream inputStream = new ObjectInputStream(
new ByteArrayInputStream(decrypted));
return (AccessToken) inputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String generateCredentialFromAccessToken(AccessToken accessToken) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(outputStream);
stream.writeObject(accessToken);
byte[] data = outputStream.toByteArray();
byte[] encryptedData = this.getCryptoManager().encrypt(data);
return this.getStringHelper().convertToHexString(encryptedData);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package org.bench4q.master.domain.service.auth;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.bench4q.master.domain.entity.User;
import org.bench4q.master.domain.repository.UserRepository;
import org.bench4q.master.helper.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AuthenticationManager {
private final int defaultExpiresTime = 3600;
private CryptoManager cryptoManager;
private UserRepository userRepository;
private StringHelper stringHelper;
private CryptoManager getCryptoManager() {
return cryptoManager;
}
@Autowired
private void setCryptoManager(CryptoManager cryptoManager) {
this.cryptoManager = cryptoManager;
}
private StringHelper getStringHelper() {
return stringHelper;
}
@Autowired
private void setStringHelper(StringHelper stringHelper) {
this.stringHelper = stringHelper;
}
private UserRepository getUserRepository() {
return userRepository;
}
@Autowired
private void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User getPrincipal(HttpServletRequest request) {
AccessToken accessToken = this.getAccessToken(request);
if (accessToken == null) {
return null;
}
return this.extractUser(accessToken);
}
public boolean checkScope(HttpServletRequest request, byte requiredScope) {
AccessToken accessToken = this.getAccessToken(request);
if (accessToken == null) {
return false;
}
return isScopeMeet(accessToken.getScope(), requiredScope);
}
public boolean isScopeMeet(byte actualScope, byte requiredScope) {
return actualScope >= requiredScope;
}
private String generateCredential(User user) {
AccessToken accessToken = this.generateAccessToken(user);
return this.generateCredentialFromAccessToken(accessToken);
}
public String generateCredential(String userName) {
return this.generateCredential(this.getUserRepository().getUser(
userName));
}
private AccessToken getAccessToken(HttpServletRequest request) {
if (request.getHeader("Authorization") == null) {
return null;
}
if (!request.getHeader("Authorization").startsWith("Bearer ")) {
return null;
}
String hex = request.getHeader("Authorization").substring(
"Bearer ".length());
byte[] bytes = this.getStringHelper().convertToBytes(hex);
return this.extractAccessToken(bytes);
}
private User extractUser(AccessToken accessToken) {
if (accessToken == null) {
return null;
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(accessToken.getGenerateTime());
calendar.add(Calendar.SECOND, accessToken.getExpiresIn());
Date expireTime = calendar.getTime();
if (expireTime.before(new Date(System.currentTimeMillis()))) {
return null;
}
return this.getUserRepository().getUser(accessToken.getUserName());
}
private AccessToken generateAccessToken(User user) {
AccessToken accessToken = new AccessToken();
accessToken.setExpiresIn(this.defaultExpiresTime);
accessToken.setGenerateTime(new Date(System.currentTimeMillis()));
accessToken.setPassword(user.getPassword());
accessToken.setUserName(user.getUserName());
accessToken.setScope(user.getScope());
return accessToken;
}
public AccessToken generateAccessToken(String userName) {
return this.generateAccessToken(this.getUserRepository().getUser(
userName));
}
private AccessToken extractAccessToken(byte[] bytes) {
try {
byte[] decrypted = this.getCryptoManager().decrypt(bytes);
ObjectInputStream inputStream = new ObjectInputStream(
new ByteArrayInputStream(decrypted));
return (AccessToken) inputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private String generateCredentialFromAccessToken(AccessToken accessToken) {
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ObjectOutputStream stream = new ObjectOutputStream(outputStream);
stream.writeObject(accessToken);
byte[] data = outputStream.toByteArray();
byte[] encryptedData = this.getCryptoManager().encrypt(data);
return this.getStringHelper().convertToHexString(encryptedData);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -1,120 +1,120 @@
package org.bench4q.master.domain.service.auth;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Enumeration;
import javax.crypto.Cipher;
import org.springframework.stereotype.Component;
@Component
public class CryptoManager {
private static final int MAX_ENCRYPT_BLOCK = 245;
private static final int MAX_DECRYPT_BLOCK = 256;
private PublicKey publicKey;
private PrivateKey privateKey;
private PublicKey getPublicKey() {
return publicKey;
}
private void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
private PrivateKey getPrivateKey() {
return privateKey;
}
private void setPrivateKey(PrivateKey privateKey) {
this.privateKey = privateKey;
}
public CryptoManager() {
try {
InputStream pfxInputStream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("org/bench4q/master/config/key.pfx");
String pfxPassword = "123456";
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(pfxInputStream, pfxPassword.toCharArray());
pfxInputStream.close();
Enumeration<String> aliases = keyStore.aliases();
if (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore
.getEntry(alias, new KeyStore.PasswordProtection(
pfxPassword.toCharArray()));
this.setPrivateKey(privateKeyEntry.getPrivateKey());
this.setPublicKey(privateKeyEntry.getCertificate()
.getPublicKey());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] encrypt(byte[] data) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, this.getPublicKey());
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public byte[] decrypt(byte[] encryptedData) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, this.getPrivateKey());
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet,
MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen
- offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package org.bench4q.master.domain.service.auth;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Enumeration;
import javax.crypto.Cipher;
import org.springframework.stereotype.Component;
@Component
public class CryptoManager {
private static final int MAX_ENCRYPT_BLOCK = 245;
private static final int MAX_DECRYPT_BLOCK = 256;
private PublicKey publicKey;
private PrivateKey privateKey;
private PublicKey getPublicKey() {
return publicKey;
}
private void setPublicKey(PublicKey publicKey) {
this.publicKey = publicKey;
}
private PrivateKey getPrivateKey() {
return privateKey;
}
private void setPrivateKey(PrivateKey privateKey) {
this.privateKey = privateKey;
}
public CryptoManager() {
try {
InputStream pfxInputStream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream("org/bench4q/master/config/key.pfx");
String pfxPassword = "123456";
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(pfxInputStream, pfxPassword.toCharArray());
pfxInputStream.close();
Enumeration<String> aliases = keyStore.aliases();
if (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore
.getEntry(alias, new KeyStore.PasswordProtection(
pfxPassword.toCharArray()));
this.setPrivateKey(privateKeyEntry.getPrivateKey());
this.setPublicKey(privateKeyEntry.getCertificate()
.getPublicKey());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public byte[] encrypt(byte[] data) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, this.getPublicKey());
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public byte[] decrypt(byte[] encryptedData) {
try {
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, this.getPrivateKey());
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet,
MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen
- offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -1,246 +1,246 @@
package org.bench4q.master.domain.service.report;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bench4q.master.domain.entity.MonitorResult;
import org.bench4q.master.domain.service.MonitorResultService;
import org.bench4q.master.domain.service.TestPlanScriptService;
import org.bench4q.master.domain.service.TestPlanService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.MonitorResultContainerModel;
import org.bench4q.share.models.monitor.MemoryModel;
import org.bench4q.share.models.monitor.NetworkInterfaceModel;
import org.bench4q.share.models.monitor.PhysicalDiskModel;
import org.bench4q.share.models.monitor.ProcessorModel;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lowagie.text.Document;
@Component
public class MonitorReportService {
public static String Processor = "ProcessorTimePercent (unit: %)";
public static String Memory = "Memory Available Memory(unit: KiloByte)";
public static String logical_Disk = "logicalDisk IO (unit: Byte)";
public static String network_Interface = "networkInterface IO (unit: Byte/second)";
private TestPlanScriptService testPlanScriptService;
private TestPlanService testPlanService;
private MonitorResultService monitorResultService;
public TestPlanScriptService getTestPlanScriptService() {
return testPlanScriptService;
}
@Autowired
public void setTestPlanScriptService(
TestPlanScriptService testPlanScriptService) {
this.testPlanScriptService = testPlanScriptService;
}
public TestPlanService getTestPlanService() {
return testPlanService;
}
@Autowired
public void setTestPlanService(TestPlanService testPlanService) {
this.testPlanService = testPlanService;
}
public MonitorResultService getMonitorResultService() {
return monitorResultService;
}
@Autowired
public void setMonitorResultService(
MonitorResultService monitorResultService) {
this.monitorResultService = monitorResultService;
}
void createMonitorResultImages(UUID testPlanRunID, Document document) throws Bench4QException {
Map<String, MonitorResultContainerModel> SUTResultMap = new HashMap<String, MonitorResultContainerModel>();
List<MonitorResult> results = this.getMonitorResultService()
.queryMonitorResults(testPlanRunID);
if (results == null) {
return;
}
for (MonitorResult result : results) {
if (result == null) {
continue;
}
buildSUTResultMap(SUTResultMap, result);
}
for (String hostName : SUTResultMap.keySet()) {
createSUTImage(hostName, SUTResultMap.get(hostName), document);
}
}
private void buildSUTResultMap(
Map<String, MonitorResultContainerModel> sUTResultMap,
MonitorResult result) {
String hostName = result.getHostNameUnderMonitor();
if (!sUTResultMap.containsKey(hostName)) {
sUTResultMap.put(result.getHostNameUnderMonitor(),
new MonitorResultContainerModel());
}
sortResultToList(result, sUTResultMap.get(hostName));
}
private void sortResultToList(final MonitorResult result,
MonitorResultContainerModel container) {
try {
if (Class.forName(result.getType()).equals(PhysicalDiskModel.class)) {
container.getLogicalDiskModels().add(
(PhysicalDiskModel) MarshalHelper.unmarshal(
PhysicalDiskModel.class, result.getContent()));
} else if (Class.forName(result.getType())
.equals(MemoryModel.class)) {
container.getMemoryModels().add(
(MemoryModel) MarshalHelper.unmarshal(
MemoryModel.class, result.getContent()));
} else if (Class.forName(result.getType()).equals(
NetworkInterfaceModel.class)) {
container.getNetWorkModels().add(
(NetworkInterfaceModel) MarshalHelper.unmarshal(
NetworkInterfaceModel.class,
result.getContent()));
} else if (Class.forName(result.getType()).equals(
ProcessorModel.class)) {
container.getProcessorModels().add(
(ProcessorModel) MarshalHelper.unmarshal(
ProcessorModel.class, result.getContent()));
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
private void createSUTImage(String hostName,
MonitorResultContainerModel container, Document document) {
try {
ReportService.addParagraph(logical_Disk, document);
createLogicalDiskImage(container.getLogicalDiskModels(), document);
ReportService.addParagraph(Memory, document);
createMemoryImage(container.getMemoryModels(), document);
ReportService.addParagraph(network_Interface, document);
// createNetworkImage(container.getNetWorkModels(), document);
ReportService.addParagraph(Processor, document);
createProcessorImage(container.getProcessorModels(), document);
} catch (Exception e) {
e.printStackTrace();
}
}
private void createProcessorImage(List<ProcessorModel> list,
Document document) throws Exception {
if (list == null || list.size() == 0) {
return;
}
int seriesCount = list.get(0).getProcessorModelList().size();
List<TimeSeries> timeSeriesArray = ReportService.buildSeries(
seriesCount, Processor);
for (ProcessorModel model : list) {
if (model == null)
continue;
for (int i = 0; i < timeSeriesArray.size(); i++) {
timeSeriesArray.get(i).addOrUpdate(
new Second(model.getSamplingTime()),
model.getProcessorModelList().get(i)
.getProcessorTimePercent());
}
}
ReportService.writeImageIntoPdf(
ReportService.buildChartStream(document, seriesCount,
timeSeriesArray, Processor).toByteArray(), document);
}
private void createMemoryImage(List<MemoryModel> list, Document document)
throws Exception {
if (list == null || list.size() == 0) {
return;
}
int seriesCount = 1;
List<TimeSeries> timeSeriesArray = ReportService.buildSeries(
seriesCount, Memory);
for (MemoryModel model : list) {
if (model == null)
continue;
for (int i = 0; i < timeSeriesArray.size(); i++) {
timeSeriesArray.get(i).addOrUpdate(
new Second(model.getSamplingTime()),
model.getAvailableKiloBytes());
}
}
ReportService.writeImageIntoPdf(
ReportService.buildChartStream(document, seriesCount,
timeSeriesArray, Memory).toByteArray(), document);
}
private void createLogicalDiskImage(List<PhysicalDiskModel> list,
Document document) throws Exception {
if (list == null || list.size() == 0) {
return;
}
int seriesCount = list.get(0).getFieFileSystemModels().size();
List<TimeSeries> timeSeriesArray = ReportService.buildSeries(
seriesCount, logical_Disk);
for (PhysicalDiskModel model : list) {
if (model == null)
continue;
for (int i = 0; i < timeSeriesArray.size(); i++) {
timeSeriesArray.get(i).addOrUpdate(
new Second(model.getSamplingTime()),
model.getFieFileSystemModels().get(i)
.getDiskTotalKBytesRate());
}
}
ReportService.writeImageIntoPdf(
ReportService.buildChartStream(document, seriesCount,
timeSeriesArray, logical_Disk).toByteArray(), document);
}
/**
* refactor this kind of use
*
* @param list
* @param document
* @throws Exception
*/
// private void createNetworkImage(List<NetworkInterfaceModel> list,
// Document document) throws Exception {
// if (list == null || list.size() == 0) {
// return;
// }
// int seriesCount = list.get(0).getNetworkList().size();
// List<TimeSeries> timeSeriesArray = ReportService.buildSeries(
// seriesCount, network_Interface);
// for (NetworkInterfaceModel model : list) {
// for (int i = 0; i < timeSeriesArray.size(); i++) {
// timeSeriesArray.get(i).addOrUpdate(
// new Second(model.getSamplingTime()),
// model.getNetworkList().get(i).getBytesTotalPerSecond());
// }
// }
// ReportService.writeImageIntoPdf(
// ReportService.buildChartStream(document, seriesCount,
// timeSeriesArray, network_Interface).toByteArray(),
// document);
// }
//}
}
package org.bench4q.master.domain.service.report;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bench4q.master.domain.entity.MonitorResult;
import org.bench4q.master.domain.service.MonitorResultService;
import org.bench4q.master.domain.service.TestPlanScriptService;
import org.bench4q.master.domain.service.TestPlanService;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.MonitorResultContainerModel;
import org.bench4q.share.models.monitor.MemoryModel;
import org.bench4q.share.models.monitor.NetworkInterfaceModel;
import org.bench4q.share.models.monitor.PhysicalDiskModel;
import org.bench4q.share.models.monitor.ProcessorModel;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lowagie.text.Document;
@Component
public class MonitorReportService {
public static String Processor = "ProcessorTimePercent (unit: %)";
public static String Memory = "Memory Available Memory(unit: KiloByte)";
public static String logical_Disk = "logicalDisk IO (unit: Byte)";
public static String network_Interface = "networkInterface IO (unit: Byte/second)";
private TestPlanScriptService testPlanScriptService;
private TestPlanService testPlanService;
private MonitorResultService monitorResultService;
public TestPlanScriptService getTestPlanScriptService() {
return testPlanScriptService;
}
@Autowired
public void setTestPlanScriptService(
TestPlanScriptService testPlanScriptService) {
this.testPlanScriptService = testPlanScriptService;
}
public TestPlanService getTestPlanService() {
return testPlanService;
}
@Autowired
public void setTestPlanService(TestPlanService testPlanService) {
this.testPlanService = testPlanService;
}
public MonitorResultService getMonitorResultService() {
return monitorResultService;
}
@Autowired
public void setMonitorResultService(
MonitorResultService monitorResultService) {
this.monitorResultService = monitorResultService;
}
void createMonitorResultImages(UUID testPlanRunID, Document document) throws Bench4QException {
Map<String, MonitorResultContainerModel> SUTResultMap = new HashMap<String, MonitorResultContainerModel>();
List<MonitorResult> results = this.getMonitorResultService()
.queryMonitorResults(testPlanRunID);
if (results == null) {
return;
}
for (MonitorResult result : results) {
if (result == null) {
continue;
}
buildSUTResultMap(SUTResultMap, result);
}
for (String hostName : SUTResultMap.keySet()) {
createSUTImage(hostName, SUTResultMap.get(hostName), document);
}
}
private void buildSUTResultMap(
Map<String, MonitorResultContainerModel> sUTResultMap,
MonitorResult result) {
String hostName = result.getHostNameUnderMonitor();
if (!sUTResultMap.containsKey(hostName)) {
sUTResultMap.put(result.getHostNameUnderMonitor(),
new MonitorResultContainerModel());
}
sortResultToList(result, sUTResultMap.get(hostName));
}
private void sortResultToList(final MonitorResult result,
MonitorResultContainerModel container) {
try {
if (Class.forName(result.getType()).equals(PhysicalDiskModel.class)) {
container.getLogicalDiskModels().add(
(PhysicalDiskModel) MarshalHelper.unmarshal(
PhysicalDiskModel.class, result.getContent()));
} else if (Class.forName(result.getType())
.equals(MemoryModel.class)) {
container.getMemoryModels().add(
(MemoryModel) MarshalHelper.unmarshal(
MemoryModel.class, result.getContent()));
} else if (Class.forName(result.getType()).equals(
NetworkInterfaceModel.class)) {
container.getNetWorkModels().add(
(NetworkInterfaceModel) MarshalHelper.unmarshal(
NetworkInterfaceModel.class,
result.getContent()));
} else if (Class.forName(result.getType()).equals(
ProcessorModel.class)) {
container.getProcessorModels().add(
(ProcessorModel) MarshalHelper.unmarshal(
ProcessorModel.class, result.getContent()));
}
} catch (Exception e) {
e.printStackTrace();
return;
}
}
private void createSUTImage(String hostName,
MonitorResultContainerModel container, Document document) {
try {
ReportService.addParagraph(logical_Disk, document);
createLogicalDiskImage(container.getLogicalDiskModels(), document);
ReportService.addParagraph(Memory, document);
createMemoryImage(container.getMemoryModels(), document);
ReportService.addParagraph(network_Interface, document);
// createNetworkImage(container.getNetWorkModels(), document);
ReportService.addParagraph(Processor, document);
createProcessorImage(container.getProcessorModels(), document);
} catch (Exception e) {
e.printStackTrace();
}
}
private void createProcessorImage(List<ProcessorModel> list,
Document document) throws Exception {
if (list == null || list.size() == 0) {
return;
}
int seriesCount = list.get(0).getProcessorModelList().size();
List<TimeSeries> timeSeriesArray = ReportService.buildSeries(
seriesCount, Processor);
for (ProcessorModel model : list) {
if (model == null)
continue;
for (int i = 0; i < timeSeriesArray.size(); i++) {
timeSeriesArray.get(i).addOrUpdate(
new Second(model.getSamplingTime()),
model.getProcessorModelList().get(i)
.getProcessorTimePercent());
}
}
ReportService.writeImageIntoPdf(
ReportService.buildChartStream(document, seriesCount,
timeSeriesArray, Processor).toByteArray(), document);
}
private void createMemoryImage(List<MemoryModel> list, Document document)
throws Exception {
if (list == null || list.size() == 0) {
return;
}
int seriesCount = 1;
List<TimeSeries> timeSeriesArray = ReportService.buildSeries(
seriesCount, Memory);
for (MemoryModel model : list) {
if (model == null)
continue;
for (int i = 0; i < timeSeriesArray.size(); i++) {
timeSeriesArray.get(i).addOrUpdate(
new Second(model.getSamplingTime()),
model.getAvailableKiloBytes());
}
}
ReportService.writeImageIntoPdf(
ReportService.buildChartStream(document, seriesCount,
timeSeriesArray, Memory).toByteArray(), document);
}
private void createLogicalDiskImage(List<PhysicalDiskModel> list,
Document document) throws Exception {
if (list == null || list.size() == 0) {
return;
}
int seriesCount = list.get(0).getFieFileSystemModels().size();
List<TimeSeries> timeSeriesArray = ReportService.buildSeries(
seriesCount, logical_Disk);
for (PhysicalDiskModel model : list) {
if (model == null)
continue;
for (int i = 0; i < timeSeriesArray.size(); i++) {
timeSeriesArray.get(i).addOrUpdate(
new Second(model.getSamplingTime()),
model.getFieFileSystemModels().get(i)
.getDiskTotalKBytesRate());
}
}
ReportService.writeImageIntoPdf(
ReportService.buildChartStream(document, seriesCount,
timeSeriesArray, logical_Disk).toByteArray(), document);
}
/**
* refactor this kind of use
*
* @param list
* @param document
* @throws Exception
*/
// private void createNetworkImage(List<NetworkInterfaceModel> list,
// Document document) throws Exception {
// if (list == null || list.size() == 0) {
// return;
// }
// int seriesCount = list.get(0).getNetworkList().size();
// List<TimeSeries> timeSeriesArray = ReportService.buildSeries(
// seriesCount, network_Interface);
// for (NetworkInterfaceModel model : list) {
// for (int i = 0; i < timeSeriesArray.size(); i++) {
// timeSeriesArray.get(i).addOrUpdate(
// new Second(model.getSamplingTime()),
// model.getNetworkList().get(i).getBytesTotalPerSecond());
// }
// }
// ReportService.writeImageIntoPdf(
// ReportService.buildChartStream(document, seriesCount,
// timeSeriesArray, network_Interface).toByteArray(),
// document);
// }
//}
}

View File

@ -1,175 +1,175 @@
package org.bench4q.master.domain.service.report;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.bench4q.master.exception.ExceptionLog;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
@Component
public class ReportService {
public static String Time = "time";
public static String PDF_FOLDER = "report";
private ScriptReportService scriptReportService;
private MonitorReportService monitorReportService;
private Logger logger = Logger.getLogger(ReportService.class);
private static int PICTURE_WIDTH = 500;
private static int PICTURE_HIGHT = 450;
public ScriptReportService getScriptReportService() {
return scriptReportService;
}
@Autowired
public void setScriptReportService(ScriptReportService scriptReportService) {
this.scriptReportService = scriptReportService;
}
public MonitorReportService getMonitorReportService() {
return monitorReportService;
}
@Autowired
public void setMonitorReportService(
MonitorReportService monitorReportService) {
this.monitorReportService = monitorReportService;
}
public byte[] createReport(UUID testPlanRunID) {
try {
if (isReportCreated(testPlanRunID)) {
return FileUtils.readFileToByteArray(new File(ReportService
.buildFilePath(testPlanRunID)));
}
isFolderExist();
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(
buildFilePath(testPlanRunID)));
document.open();
this.getScriptReportService().createScriptsResultsImage(
testPlanRunID, document);
this.getMonitorReportService().createMonitorResultImages(
testPlanRunID, document);
document.close();
return FileUtils.readFileToByteArray(new File(
buildFilePath(testPlanRunID)));
} catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
}
public boolean isReportCreated(UUID testPlanRunID) {
return new File(buildFilePath(testPlanRunID)).exists();
}
public static String buildFilePath(UUID testPlanRunID) {
return PDF_FOLDER + System.getProperty("file.separator")
+ testPlanRunID + ".pdf";
}
private void isFolderExist() {
try {
if (!new File(PDF_FOLDER).isDirectory()) {
new File(PDF_FOLDER).mkdir();
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
static void addParagraph(String content, Document document)
throws DocumentException {
Paragraph paragraph = new Paragraph(content);
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
}
public static ByteArrayOutputStream buildChartStream(Document document,
int seriesCount, List<TimeSeries> timeSeriesArray, String value)
throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JFreeChart chart = ChartFactory.createTimeSeriesChart(value,
ReportService.Time, value, buildDataSet(timeSeriesArray), true,
true, true);
adjustChartFont(value, chart);
ChartUtilities.writeChartAsPNG(outputStream, chart, PICTURE_WIDTH,
PICTURE_HIGHT);
return outputStream;
}
private static void adjustChartFont(String value, JFreeChart chart) {
Font xfont = new Font("<EFBFBD><EFBFBD><EFBFBD><EFBFBD>", Font.CENTER_BASELINE, 14);// X
Font yfont = new Font("<EFBFBD><EFBFBD><EFBFBD><EFBFBD>", Font.CENTER_BASELINE, 14);// Y
Font kfont = new Font("<EFBFBD><EFBFBD><EFBFBD><EFBFBD>", Font.CENTER_BASELINE, 12);//
Font titleFont = new Font("΢<EFBFBD><EFBFBD><EFBFBD>ź<EFBFBD>", Font.CENTER_BASELINE, 16); // title
chart.setBorderStroke(new BasicStroke(1));
chart.setBorderVisible(true);
chart.setBorderPaint(Color.cyan);
chart.setTitle(new TextTitle(value, titleFont));
XYPlot plot = chart.getXYPlot();
plot.getRangeAxis().setLabelFont(yfont);
plot.getRangeAxis().setTickLabelFont(kfont);
plot.getDomainAxis().setLabelFont(xfont);
plot.getDomainAxis().setTickLabelFont(kfont);
chart.setBackgroundPaint(java.awt.Color.white);
}
public static List<TimeSeries> buildSeries(int seriesCount, String mainTitle) {
List<TimeSeries> timeSeriesArray = new ArrayList<TimeSeries>(
seriesCount);
for (int i = 0; i < seriesCount; i++) {
timeSeriesArray.add(new TimeSeries(mainTitle + "-" + i));
}
return timeSeriesArray;
}
static TimeSeriesCollection buildDataSet(
final List<TimeSeries> timeSeriesArray) {
TimeSeriesCollection lineDataset = new TimeSeriesCollection();
if (timeSeriesArray == null) {
return null;
}
for (TimeSeries timeSeries : timeSeriesArray) {
lineDataset.addSeries(timeSeries);
}
return lineDataset;
}
public static void writeImageIntoPdf(byte[] buffer, Document document)
throws Exception {
Image image = Image.getInstance(buffer);
image.setAlignment(Element.ALIGN_CENTER);
document.add(image);
}
}
package org.bench4q.master.domain.service.report;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.bench4q.master.exception.ExceptionLog;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Image;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
@Component
public class ReportService {
public static String Time = "time";
public static String PDF_FOLDER = "report";
private ScriptReportService scriptReportService;
private MonitorReportService monitorReportService;
private Logger logger = Logger.getLogger(ReportService.class);
private static int PICTURE_WIDTH = 500;
private static int PICTURE_HIGHT = 450;
public ScriptReportService getScriptReportService() {
return scriptReportService;
}
@Autowired
public void setScriptReportService(ScriptReportService scriptReportService) {
this.scriptReportService = scriptReportService;
}
public MonitorReportService getMonitorReportService() {
return monitorReportService;
}
@Autowired
public void setMonitorReportService(
MonitorReportService monitorReportService) {
this.monitorReportService = monitorReportService;
}
public byte[] createReport(UUID testPlanRunID) {
try {
if (isReportCreated(testPlanRunID)) {
return FileUtils.readFileToByteArray(new File(ReportService
.buildFilePath(testPlanRunID)));
}
isFolderExist();
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(
buildFilePath(testPlanRunID)));
document.open();
this.getScriptReportService().createScriptsResultsImage(
testPlanRunID, document);
this.getMonitorReportService().createMonitorResultImages(
testPlanRunID, document);
document.close();
return FileUtils.readFileToByteArray(new File(
buildFilePath(testPlanRunID)));
} catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
}
public boolean isReportCreated(UUID testPlanRunID) {
return new File(buildFilePath(testPlanRunID)).exists();
}
public static String buildFilePath(UUID testPlanRunID) {
return PDF_FOLDER + System.getProperty("file.separator")
+ testPlanRunID + ".pdf";
}
private void isFolderExist() {
try {
if (!new File(PDF_FOLDER).isDirectory()) {
new File(PDF_FOLDER).mkdir();
}
} catch (SecurityException e) {
e.printStackTrace();
}
}
static void addParagraph(String content, Document document)
throws DocumentException {
Paragraph paragraph = new Paragraph(content);
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
}
public static ByteArrayOutputStream buildChartStream(Document document,
int seriesCount, List<TimeSeries> timeSeriesArray, String value)
throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JFreeChart chart = ChartFactory.createTimeSeriesChart(value,
ReportService.Time, value, buildDataSet(timeSeriesArray), true,
true, true);
adjustChartFont(value, chart);
ChartUtilities.writeChartAsPNG(outputStream, chart, PICTURE_WIDTH,
PICTURE_HIGHT);
return outputStream;
}
private static void adjustChartFont(String value, JFreeChart chart) {
Font xfont = new Font("<EFBFBD><EFBFBD><EFBFBD><EFBFBD>", Font.CENTER_BASELINE, 14);// X
Font yfont = new Font("<EFBFBD><EFBFBD><EFBFBD><EFBFBD>", Font.CENTER_BASELINE, 14);// Y
Font kfont = new Font("<EFBFBD><EFBFBD><EFBFBD><EFBFBD>", Font.CENTER_BASELINE, 12);//
Font titleFont = new Font("΢<EFBFBD><EFBFBD><EFBFBD>ź<EFBFBD>", Font.CENTER_BASELINE, 16); // title
chart.setBorderStroke(new BasicStroke(1));
chart.setBorderVisible(true);
chart.setBorderPaint(Color.cyan);
chart.setTitle(new TextTitle(value, titleFont));
XYPlot plot = chart.getXYPlot();
plot.getRangeAxis().setLabelFont(yfont);
plot.getRangeAxis().setTickLabelFont(kfont);
plot.getDomainAxis().setLabelFont(xfont);
plot.getDomainAxis().setTickLabelFont(kfont);
chart.setBackgroundPaint(java.awt.Color.white);
}
public static List<TimeSeries> buildSeries(int seriesCount, String mainTitle) {
List<TimeSeries> timeSeriesArray = new ArrayList<TimeSeries>(
seriesCount);
for (int i = 0; i < seriesCount; i++) {
timeSeriesArray.add(new TimeSeries(mainTitle + "-" + i));
}
return timeSeriesArray;
}
static TimeSeriesCollection buildDataSet(
final List<TimeSeries> timeSeriesArray) {
TimeSeriesCollection lineDataset = new TimeSeriesCollection();
if (timeSeriesArray == null) {
return null;
}
for (TimeSeries timeSeries : timeSeriesArray) {
lineDataset.addSeries(timeSeries);
}
return lineDataset;
}
public static void writeImageIntoPdf(byte[] buffer, Document document)
throws Exception {
Image image = Image.getInstance(buffer);
image.setAlignment(Element.ALIGN_CENTER);
document.add(image);
}
}

View File

@ -1,122 +1,122 @@
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bench4q.share.models.agent.BehaviorBriefModel;
import org.bench4q.share.models.agent.BehaviorStatusCodeResultModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
public class BehaviorsBriefStatistics extends ScriptStatistics {
private Map<Integer, Map<Integer, BehaviorStatusCodeResultModel>> map;
private Map<Integer, String> idUrlMap;
private Map<Integer, Map<Integer, BehaviorStatusCodeResultModel>> getMap() {
return map;
}
private void setMap(
Map<Integer, Map<Integer, BehaviorStatusCodeResultModel>> map) {
this.map = map;
}
public Map<Integer, String> getIdUrlMap() {
return idUrlMap;
}
public void setIdUrlMap(Map<Integer, String> idUrlMap) {
this.idUrlMap = idUrlMap;
}
public BehaviorsBriefStatistics() {
this.setMap(new HashMap<Integer, Map<Integer, BehaviorStatusCodeResultModel>>());
this.setIdUrlMap(new HashMap<Integer, String>());
}
public ScriptBehaviorsBriefModel getStatistics() {
ScriptBehaviorsBriefModel result = new ScriptBehaviorsBriefModel();
AgentBehaviorsBriefModel agentBehaviorsBriefModel = new AgentBehaviorsBriefModel();
List<BehaviorBriefModel> list = new ArrayList<BehaviorBriefModel>();
for (int behaviorId : this.getMap().keySet()) {
BehaviorBriefModel behaviorBriefModel = new BehaviorBriefModel();
behaviorBriefModel.setBehaviorId(behaviorId);
behaviorBriefModel.setBehaviorUrl(this.getIdUrlMap()
.get(behaviorId));
List<BehaviorStatusCodeResultModel> statusList = new ArrayList<BehaviorStatusCodeResultModel>();
for (int statusCode : this.getMap().get(behaviorId).keySet()) {
statusList.add(getCopy(behaviorId, statusCode));
}
behaviorBriefModel.setDetailStatusCodeResultModels(statusList);
list.add(behaviorBriefModel);
}
agentBehaviorsBriefModel.setBehaviorBriefModels(list);
result.setTestBehaviorsBriefModel(agentBehaviorsBriefModel);
makeUpResultModelWithSamplingTime(result);
return result;
}
private BehaviorStatusCodeResultModel getCopy(int behaviorId, int statusCode) {
BehaviorStatusCodeResultModel statusInMap = this.getMap()
.get(behaviorId).get(statusCode);
BehaviorStatusCodeResultModel ret = new BehaviorStatusCodeResultModel();
ret.setStatusCode(statusCode);
ret.setContentLength(statusInMap.getContentLength());
ret.setContentType(statusInMap.getContentType());
ret.setCount(statusInMap.getCount());
ret.setMaxResponseTime(statusInMap.getMaxResponseTime());
ret.setMinResponseTime(statusInMap.getMinResponseTime());
ret.setTotalResponseTimeThisTime(statusInMap
.getTotalResponseTimeThisTime());
return ret;
}
public void add(DataStatisticsModel dataUnit) {
if (!(dataUnit instanceof AgentBehaviorsBriefModel)) {
return;
}
AgentBehaviorsBriefModel input = (AgentBehaviorsBriefModel) dataUnit;
for (BehaviorBriefModel behaviorBriefModel : input
.getBehaviorBriefModels()) {
guardAllMapsKeyExists(behaviorBriefModel);
Map<Integer, BehaviorStatusCodeResultModel> behaviorStatusMap = this
.getMap().get(behaviorBriefModel.getBehaviorId());
for (BehaviorStatusCodeResultModel newOne : behaviorBriefModel
.getDetailStatusCodeResultModels()) {
if (!behaviorStatusMap.containsKey(newOne.getStatusCode())) {
behaviorStatusMap.put(newOne.getStatusCode(), newOne);
continue;
}
BehaviorStatusCodeResultModel origin = behaviorStatusMap
.get(newOne.getStatusCode());
origin.setContentLength(origin.getContentLength()
+ newOne.getContentLength());
origin.setCount(origin.getCount() + newOne.getCount());
origin.setTotalResponseTimeThisTime(origin
.getTotalResponseTimeThisTime()
+ newOne.getTotalResponseTimeThisTime());
if (newOne.getMaxResponseTime() > origin.getMaxResponseTime()) {
origin.setMaxResponseTime(newOne.getMaxResponseTime());
}
if (newOne.getMinResponseTime() < origin.getMinResponseTime()) {
origin.setMinResponseTime(newOne.getMinResponseTime());
}
}
}
}
private synchronized void guardAllMapsKeyExists(
BehaviorBriefModel behaviorBriefModel) {
if (!this.getMap().containsKey(behaviorBriefModel.getBehaviorId())) {
this.getMap().put(behaviorBriefModel.getBehaviorId(),
new HashMap<Integer, BehaviorStatusCodeResultModel>());
}
if (!this.getIdUrlMap().containsKey(behaviorBriefModel.getBehaviorId())) {
this.getIdUrlMap().put(behaviorBriefModel.getBehaviorId(),
behaviorBriefModel.getBehaviorUrl());
}
}
}
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bench4q.share.models.agent.BehaviorBriefModel;
import org.bench4q.share.models.agent.BehaviorStatusCodeResultModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
public class BehaviorsBriefStatistics extends ScriptStatistics {
private Map<Integer, Map<Integer, BehaviorStatusCodeResultModel>> map;
private Map<Integer, String> idUrlMap;
private Map<Integer, Map<Integer, BehaviorStatusCodeResultModel>> getMap() {
return map;
}
private void setMap(
Map<Integer, Map<Integer, BehaviorStatusCodeResultModel>> map) {
this.map = map;
}
public Map<Integer, String> getIdUrlMap() {
return idUrlMap;
}
public void setIdUrlMap(Map<Integer, String> idUrlMap) {
this.idUrlMap = idUrlMap;
}
public BehaviorsBriefStatistics() {
this.setMap(new HashMap<Integer, Map<Integer, BehaviorStatusCodeResultModel>>());
this.setIdUrlMap(new HashMap<Integer, String>());
}
public ScriptBehaviorsBriefModel getStatistics() {
ScriptBehaviorsBriefModel result = new ScriptBehaviorsBriefModel();
AgentBehaviorsBriefModel agentBehaviorsBriefModel = new AgentBehaviorsBriefModel();
List<BehaviorBriefModel> list = new ArrayList<BehaviorBriefModel>();
for (int behaviorId : this.getMap().keySet()) {
BehaviorBriefModel behaviorBriefModel = new BehaviorBriefModel();
behaviorBriefModel.setBehaviorId(behaviorId);
behaviorBriefModel.setBehaviorUrl(this.getIdUrlMap()
.get(behaviorId));
List<BehaviorStatusCodeResultModel> statusList = new ArrayList<BehaviorStatusCodeResultModel>();
for (int statusCode : this.getMap().get(behaviorId).keySet()) {
statusList.add(getCopy(behaviorId, statusCode));
}
behaviorBriefModel.setDetailStatusCodeResultModels(statusList);
list.add(behaviorBriefModel);
}
agentBehaviorsBriefModel.setBehaviorBriefModels(list);
result.setTestBehaviorsBriefModel(agentBehaviorsBriefModel);
makeUpResultModelWithSamplingTime(result);
return result;
}
private BehaviorStatusCodeResultModel getCopy(int behaviorId, int statusCode) {
BehaviorStatusCodeResultModel statusInMap = this.getMap()
.get(behaviorId).get(statusCode);
BehaviorStatusCodeResultModel ret = new BehaviorStatusCodeResultModel();
ret.setStatusCode(statusCode);
ret.setContentLength(statusInMap.getContentLength());
ret.setContentType(statusInMap.getContentType());
ret.setCount(statusInMap.getCount());
ret.setMaxResponseTime(statusInMap.getMaxResponseTime());
ret.setMinResponseTime(statusInMap.getMinResponseTime());
ret.setTotalResponseTimeThisTime(statusInMap
.getTotalResponseTimeThisTime());
return ret;
}
public void add(DataStatisticsModel dataUnit) {
if (!(dataUnit instanceof AgentBehaviorsBriefModel)) {
return;
}
AgentBehaviorsBriefModel input = (AgentBehaviorsBriefModel) dataUnit;
for (BehaviorBriefModel behaviorBriefModel : input
.getBehaviorBriefModels()) {
guardAllMapsKeyExists(behaviorBriefModel);
Map<Integer, BehaviorStatusCodeResultModel> behaviorStatusMap = this
.getMap().get(behaviorBriefModel.getBehaviorId());
for (BehaviorStatusCodeResultModel newOne : behaviorBriefModel
.getDetailStatusCodeResultModels()) {
if (!behaviorStatusMap.containsKey(newOne.getStatusCode())) {
behaviorStatusMap.put(newOne.getStatusCode(), newOne);
continue;
}
BehaviorStatusCodeResultModel origin = behaviorStatusMap
.get(newOne.getStatusCode());
origin.setContentLength(origin.getContentLength()
+ newOne.getContentLength());
origin.setCount(origin.getCount() + newOne.getCount());
origin.setTotalResponseTimeThisTime(origin
.getTotalResponseTimeThisTime()
+ newOne.getTotalResponseTimeThisTime());
if (newOne.getMaxResponseTime() > origin.getMaxResponseTime()) {
origin.setMaxResponseTime(newOne.getMaxResponseTime());
}
if (newOne.getMinResponseTime() < origin.getMinResponseTime()) {
origin.setMinResponseTime(newOne.getMinResponseTime());
}
}
}
}
private synchronized void guardAllMapsKeyExists(
BehaviorBriefModel behaviorBriefModel) {
if (!this.getMap().containsKey(behaviorBriefModel.getBehaviorId())) {
this.getMap().put(behaviorBriefModel.getBehaviorId(),
new HashMap<Integer, BehaviorStatusCodeResultModel>());
}
if (!this.getIdUrlMap().containsKey(behaviorBriefModel.getBehaviorId())) {
this.getIdUrlMap().put(behaviorBriefModel.getBehaviorId(),
behaviorBriefModel.getBehaviorUrl());
}
}
}

View File

@ -1,19 +1,19 @@
package org.bench4q.master.domain.valueobject.datastatistics;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
public interface DataStatistics {
public void add(DataStatisticsModel dataUnit);
public Object getStatistics();
public class DefaultStatistics implements DataStatistics {
public void add(DataStatisticsModel dataUnit) {
}
public Object getStatistics() {
return null;
}
}
}
package org.bench4q.master.domain.valueobject.datastatistics;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
public interface DataStatistics {
public void add(DataStatisticsModel dataUnit);
public Object getStatistics();
public class DefaultStatistics implements DataStatistics {
public void add(DataStatisticsModel dataUnit) {
}
public Object getStatistics() {
return null;
}
}
}

View File

@ -1,73 +1,73 @@
package org.bench4q.master.domain.valueobject.datastatistics;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.master.statistics.ScriptPageBriefModel;
/**
*
* @author coderfengyun :This class is only statistics for One page, should
* construct it once each page;
* @Tip countFromBegin : Because of the statistics means that just accumulate
* the "countFromBegin" field of AgentPageBriefModel, so I can just take it
* as a temperary field for this class
*/
public class PageBriefStatistics extends ScriptStatistics {
private long countFromBegin;
private long maxResponseTimeFromBegin;
private long minResponseTimeFromBegin;
private long totalResponseTimeThisTime;
private long countThisTime;
private long latestResponseTime;
public PageBriefStatistics() {
resetTemperaryFields();
this.maxResponseTimeFromBegin = Long.MIN_VALUE;
this.minResponseTimeFromBegin = Long.MAX_VALUE;
}
private void resetTemperaryFields() {
this.totalResponseTimeThisTime = 0;
this.countThisTime = 0;
this.countFromBegin = 0;
}
public void add(DataStatisticsModel dataUnit) {
if (!(dataUnit instanceof AgentPageBriefModel)) {
return;
}
add((AgentPageBriefModel) dataUnit);
}
private void add(AgentPageBriefModel pageBriefModel) {
this.countFromBegin += pageBriefModel.getCountFromBegin();
this.countThisTime += pageBriefModel.getCountThisTime();
this.totalResponseTimeThisTime += pageBriefModel
.getTotalResponseTimeThisTime();
this.latestResponseTime = pageBriefModel.getLatestResponseTime();
if (pageBriefModel.getMaxResponseTimeFromBegin() > this.maxResponseTimeFromBegin) {
this.maxResponseTimeFromBegin = pageBriefModel
.getMaxResponseTimeFromBegin();
}
if (pageBriefModel.getMinResponseTimeFromBegin() < this.minResponseTimeFromBegin) {
this.minResponseTimeFromBegin = pageBriefModel
.getMinResponseTimeFromBegin();
}
}
public Object getStatistics() {
ScriptPageBriefModel result = new ScriptPageBriefModel();
result.setCountFromBegin(this.countFromBegin);
result.setLatestResponseTime(this.latestResponseTime);
result.setMaxResponseTimeFromBegin(this.maxResponseTimeFromBegin);
result.setMinResponseTimeFromBegin(this.minResponseTimeFromBegin);
if (this.countThisTime > 0) {
result.setAverageResponseTimeThisTime(this.totalResponseTimeThisTime
/ this.countThisTime);
}
resetTemperaryFields();
makeUpResultModelWithSamplingTime(result);
return result;
}
}
package org.bench4q.master.domain.valueobject.datastatistics;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.master.statistics.ScriptPageBriefModel;
/**
*
* @author coderfengyun :This class is only statistics for One page, should
* construct it once each page;
* @Tip countFromBegin : Because of the statistics means that just accumulate
* the "countFromBegin" field of AgentPageBriefModel, so I can just take it
* as a temperary field for this class
*/
public class PageBriefStatistics extends ScriptStatistics {
private long countFromBegin;
private long maxResponseTimeFromBegin;
private long minResponseTimeFromBegin;
private long totalResponseTimeThisTime;
private long countThisTime;
private long latestResponseTime;
public PageBriefStatistics() {
resetTemperaryFields();
this.maxResponseTimeFromBegin = Long.MIN_VALUE;
this.minResponseTimeFromBegin = Long.MAX_VALUE;
}
private void resetTemperaryFields() {
this.totalResponseTimeThisTime = 0;
this.countThisTime = 0;
this.countFromBegin = 0;
}
public void add(DataStatisticsModel dataUnit) {
if (!(dataUnit instanceof AgentPageBriefModel)) {
return;
}
add((AgentPageBriefModel) dataUnit);
}
private void add(AgentPageBriefModel pageBriefModel) {
this.countFromBegin += pageBriefModel.getCountFromBegin();
this.countThisTime += pageBriefModel.getCountThisTime();
this.totalResponseTimeThisTime += pageBriefModel
.getTotalResponseTimeThisTime();
this.latestResponseTime = pageBriefModel.getLatestResponseTime();
if (pageBriefModel.getMaxResponseTimeFromBegin() > this.maxResponseTimeFromBegin) {
this.maxResponseTimeFromBegin = pageBriefModel
.getMaxResponseTimeFromBegin();
}
if (pageBriefModel.getMinResponseTimeFromBegin() < this.minResponseTimeFromBegin) {
this.minResponseTimeFromBegin = pageBriefModel
.getMinResponseTimeFromBegin();
}
}
public Object getStatistics() {
ScriptPageBriefModel result = new ScriptPageBriefModel();
result.setCountFromBegin(this.countFromBegin);
result.setLatestResponseTime(this.latestResponseTime);
result.setMaxResponseTimeFromBegin(this.maxResponseTimeFromBegin);
result.setMinResponseTimeFromBegin(this.minResponseTimeFromBegin);
if (this.countThisTime > 0) {
result.setAverageResponseTimeThisTime(this.totalResponseTimeThisTime
/ this.countThisTime);
}
resetTemperaryFields();
makeUpResultModelWithSamplingTime(result);
return result;
}
}

View File

@ -1,61 +1,61 @@
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.HashMap;
import java.util.Map;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.bench4q.share.models.agent.statistics.AgentPagesBriefModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.master.statistics.ScriptPageBriefModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
public class PagesBriefStatistics extends ScriptStatistics {
private Map<Integer, PageBriefStatistics> map;
private Map<Integer, PageBriefStatistics> getMap() {
return map;
}
private void setMap(Map<Integer, PageBriefStatistics> map) {
this.map = map;
}
public PagesBriefStatistics() {
this.setMap(new HashMap<Integer, PageBriefStatistics>());
}
public void add(DataStatisticsModel dataUnit) {
if (dataUnit instanceof AgentPagesBriefModel) {
add((AgentPagesBriefModel) dataUnit);
}
}
private void add(AgentPagesBriefModel agentPagesBriefModel) {
for (AgentPageBriefModel unit : agentPagesBriefModel
.getPageBriefModels()) {
this.getValueFromMap(unit.getPageId()).add(unit);
}
}
private PageBriefStatistics getValueFromMap(int key) {
guardMapKeyExists(key);
return this.getMap().get(key);
}
private synchronized void guardMapKeyExists(int key) {
if (!this.getMap().containsKey(key)) {
this.getMap().put(key, new PageBriefStatistics());
}
}
public Object getStatistics() {
ScriptPagesBriefModel scriptPagesBriefModel = new ScriptPagesBriefModel();
for (Integer key : this.getMap().keySet()) {
scriptPagesBriefModel.getScriptPageBriefModels().add(
(ScriptPageBriefModel) this.getValueFromMap(key)
.getStatistics());
}
return scriptPagesBriefModel;
}
}
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.HashMap;
import java.util.Map;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.bench4q.share.models.agent.statistics.AgentPagesBriefModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.master.statistics.ScriptPageBriefModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
public class PagesBriefStatistics extends ScriptStatistics {
private Map<Integer, PageBriefStatistics> map;
private Map<Integer, PageBriefStatistics> getMap() {
return map;
}
private void setMap(Map<Integer, PageBriefStatistics> map) {
this.map = map;
}
public PagesBriefStatistics() {
this.setMap(new HashMap<Integer, PageBriefStatistics>());
}
public void add(DataStatisticsModel dataUnit) {
if (dataUnit instanceof AgentPagesBriefModel) {
add((AgentPagesBriefModel) dataUnit);
}
}
private void add(AgentPagesBriefModel agentPagesBriefModel) {
for (AgentPageBriefModel unit : agentPagesBriefModel
.getPageBriefModels()) {
this.getValueFromMap(unit.getPageId()).add(unit);
}
}
private PageBriefStatistics getValueFromMap(int key) {
guardMapKeyExists(key);
return this.getMap().get(key);
}
private synchronized void guardMapKeyExists(int key) {
if (!this.getMap().containsKey(key)) {
this.getMap().put(key, new PageBriefStatistics());
}
}
public Object getStatistics() {
ScriptPagesBriefModel scriptPagesBriefModel = new ScriptPagesBriefModel();
for (Integer key : this.getMap().keySet()) {
scriptPagesBriefModel.getScriptPageBriefModels().add(
(ScriptPageBriefModel) this.getValueFromMap(key)
.getStatistics());
}
return scriptPagesBriefModel;
}
}

View File

@ -1,154 +1,154 @@
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.bench4q.master.domain.RunningAgentInterface;
import org.bench4q.master.helper.ApplicationContextHelper;
import org.bench4q.master.infrastructure.communication.AgentMessenger;
import org.bench4q.share.models.agent.TestBriefStatusModel;
import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel;
import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel;
import org.bench4q.share.models.agent.statistics.AgentPagesBriefModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
import org.bench4q.share.models.master.statistics.ScriptResultModel;
public class RunningScriptSampler {
private List<DataStatistics> dataStatisticsList;
private List<RunningAgentInterface> runningAgents;
private AgentMessenger agentMessenger;
private List<DataStatistics> getDataStatisticsList() {
return dataStatisticsList;
}
private void setDataStatisticsList(List<DataStatistics> dataStatisticsList) {
this.dataStatisticsList = dataStatisticsList;
}
public List<RunningAgentInterface> getRunningAgents() {
return runningAgents;
}
private void setRunningAgents(List<RunningAgentInterface> runningAgents) {
this.runningAgents = runningAgents;
}
private AgentMessenger getAgentMessenger() {
return agentMessenger;
}
private void setAgentMessenger(AgentMessenger agentMessenger) {
this.agentMessenger = agentMessenger;
}
private RunningScriptSampler() {
this.setDataStatisticsList(new ArrayList<DataStatistics>());
this.getDataStatisticsList().add(new ScriptBriefStatistics());
this.getDataStatisticsList().add(new BehaviorsBriefStatistics());
this.getDataStatisticsList().add(new PagesBriefStatistics());
this.setAgentMessenger(ApplicationContextHelper.getContext().getBean(
AgentMessenger.class));
this.setRunningAgents(new LinkedList<RunningAgentInterface>());
}
public RunningScriptSampler(
Collection<? extends RunningAgentInterface> runningAgents) {
this();
this.getRunningAgents().addAll(runningAgents);
}
public ScriptResultModel getResultModelFromAgent() throws JAXBException {
for (RunningAgentInterface runningAgent : getRunningAgents()) {
if (runningAgent.isBreakDown()) {
continue;
}
TestBriefStatusModel testBriefStatusModel = this
.getAgentMessenger().scriptBriefAll(
runningAgent.getAgent(),
runningAgent.getAgentRunId());
addScriptResultModelStatistics(testBriefStatusModel);
}
return getScriptResultModel();
}
private void addScriptResultModelStatistics(
TestBriefStatusModel testBriefStatusModel) throws JAXBException {
addAgentBriefStatusModel(testBriefStatusModel.getScenarioBriefModel());
addScriptBehaviorsBriefModel(testBriefStatusModel
.getBehaviorsBriefModel());
addScriptPagesBriefModel(testBriefStatusModel.getPagesBriefModel());
}
private void addAgentBriefStatusModel(
AgentBriefStatusModel agentBriefStatusModel) {
if (agentBriefStatusModel != null)
getScriptBriefStatistics().add(agentBriefStatusModel);
}
private void addScriptPagesBriefModel(
AgentPagesBriefModel agentPagesBriefModel) {
if (agentPagesBriefModel != null)
this.getPagesBriefStatistics().add(agentPagesBriefModel);
}
private void addScriptBehaviorsBriefModel(
AgentBehaviorsBriefModel agentBehaviorsBriefModel) throws JAXBException {
if (agentBehaviorsBriefModel != null) {
getBehaviorsBriefStatistics().add(agentBehaviorsBriefModel);
}
}
private ScriptResultModel getScriptResultModel() {
ScriptResultModel scriptResultModel = new ScriptResultModel();
scriptResultModel
.setScriptBehaviorsBriefModel((ScriptBehaviorsBriefModel) getBehaviorsBriefStatistics()
.getStatistics());
scriptResultModel
.setScriptBriefResultModel((ScriptBriefResultModel) getScriptBriefStatistics()
.getStatistics());
scriptResultModel
.setScriptPagesBriefModel((ScriptPagesBriefModel) getPagesBriefStatistics()
.getStatistics());
return scriptResultModel;
}
private DataStatistics getScriptBriefStatistics() {
return getSpecificDataStatistics(ScriptBriefStatistics.class);
}
private DataStatistics getBehaviorsBriefStatistics() {
return getSpecificDataStatistics(BehaviorsBriefStatistics.class);
}
public DataStatistics getPagesBriefStatistics() {
return getSpecificDataStatistics(PagesBriefStatistics.class);
}
private DataStatistics getSpecificDataStatistics(
Class<? extends DataStatistics> dataStatisticsClass) {
for (DataStatistics dataStatistics : this.getDataStatisticsList()) {
if (dataStatistics.getClass().equals(dataStatisticsClass)) {
return dataStatistics;
}
}
return new ScriptStatistics() {
public void add(DataStatisticsModel dataUnit) {
}
public Object getStatistics() {
return null;
}
};
}
}
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import javax.xml.bind.JAXBException;
import org.bench4q.master.domain.RunningAgentInterface;
import org.bench4q.master.helper.ApplicationContextHelper;
import org.bench4q.master.infrastructure.communication.AgentMessenger;
import org.bench4q.share.models.agent.TestBriefStatusModel;
import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel;
import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel;
import org.bench4q.share.models.agent.statistics.AgentPagesBriefModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
import org.bench4q.share.models.master.statistics.ScriptResultModel;
public class RunningScriptSampler {
private List<DataStatistics> dataStatisticsList;
private List<RunningAgentInterface> runningAgents;
private AgentMessenger agentMessenger;
private List<DataStatistics> getDataStatisticsList() {
return dataStatisticsList;
}
private void setDataStatisticsList(List<DataStatistics> dataStatisticsList) {
this.dataStatisticsList = dataStatisticsList;
}
public List<RunningAgentInterface> getRunningAgents() {
return runningAgents;
}
private void setRunningAgents(List<RunningAgentInterface> runningAgents) {
this.runningAgents = runningAgents;
}
private AgentMessenger getAgentMessenger() {
return agentMessenger;
}
private void setAgentMessenger(AgentMessenger agentMessenger) {
this.agentMessenger = agentMessenger;
}
private RunningScriptSampler() {
this.setDataStatisticsList(new ArrayList<DataStatistics>());
this.getDataStatisticsList().add(new ScriptBriefStatistics());
this.getDataStatisticsList().add(new BehaviorsBriefStatistics());
this.getDataStatisticsList().add(new PagesBriefStatistics());
this.setAgentMessenger(ApplicationContextHelper.getContext().getBean(
AgentMessenger.class));
this.setRunningAgents(new LinkedList<RunningAgentInterface>());
}
public RunningScriptSampler(
Collection<? extends RunningAgentInterface> runningAgents) {
this();
this.getRunningAgents().addAll(runningAgents);
}
public ScriptResultModel getResultModelFromAgent() throws JAXBException {
for (RunningAgentInterface runningAgent : getRunningAgents()) {
if (runningAgent.isBreakDown()) {
continue;
}
TestBriefStatusModel testBriefStatusModel = this
.getAgentMessenger().scriptBriefAll(
runningAgent.getAgent(),
runningAgent.getAgentRunId());
addScriptResultModelStatistics(testBriefStatusModel);
}
return getScriptResultModel();
}
private void addScriptResultModelStatistics(
TestBriefStatusModel testBriefStatusModel) throws JAXBException {
addAgentBriefStatusModel(testBriefStatusModel.getScenarioBriefModel());
addScriptBehaviorsBriefModel(testBriefStatusModel
.getBehaviorsBriefModel());
addScriptPagesBriefModel(testBriefStatusModel.getPagesBriefModel());
}
private void addAgentBriefStatusModel(
AgentBriefStatusModel agentBriefStatusModel) {
if (agentBriefStatusModel != null)
getScriptBriefStatistics().add(agentBriefStatusModel);
}
private void addScriptPagesBriefModel(
AgentPagesBriefModel agentPagesBriefModel) {
if (agentPagesBriefModel != null)
this.getPagesBriefStatistics().add(agentPagesBriefModel);
}
private void addScriptBehaviorsBriefModel(
AgentBehaviorsBriefModel agentBehaviorsBriefModel) throws JAXBException {
if (agentBehaviorsBriefModel != null) {
getBehaviorsBriefStatistics().add(agentBehaviorsBriefModel);
}
}
private ScriptResultModel getScriptResultModel() {
ScriptResultModel scriptResultModel = new ScriptResultModel();
scriptResultModel
.setScriptBehaviorsBriefModel((ScriptBehaviorsBriefModel) getBehaviorsBriefStatistics()
.getStatistics());
scriptResultModel
.setScriptBriefResultModel((ScriptBriefResultModel) getScriptBriefStatistics()
.getStatistics());
scriptResultModel
.setScriptPagesBriefModel((ScriptPagesBriefModel) getPagesBriefStatistics()
.getStatistics());
return scriptResultModel;
}
private DataStatistics getScriptBriefStatistics() {
return getSpecificDataStatistics(ScriptBriefStatistics.class);
}
private DataStatistics getBehaviorsBriefStatistics() {
return getSpecificDataStatistics(BehaviorsBriefStatistics.class);
}
public DataStatistics getPagesBriefStatistics() {
return getSpecificDataStatistics(PagesBriefStatistics.class);
}
private DataStatistics getSpecificDataStatistics(
Class<? extends DataStatistics> dataStatisticsClass) {
for (DataStatistics dataStatistics : this.getDataStatisticsList()) {
if (dataStatistics.getClass().equals(dataStatisticsClass)) {
return dataStatistics;
}
}
return new ScriptStatistics() {
public void add(DataStatisticsModel dataUnit) {
}
public Object getStatistics() {
return null;
}
};
}
}

View File

@ -1,214 +1,214 @@
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.Date;
import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
public class ScriptBriefStatistics extends ScriptStatistics {
private long totalFailCountThisTime;
private long totalSuccessCountThisTime;
private long totalSquareResponseTime;
private long totalFailThroughputThisTime;
private long totalSuccessThroughputThisTime;
private long minResponseTimeThisTime;
private long maxResponseTimeThisTime;
private long totalResponseTimeThisTime;
private long totalFailCountFromBegin;
private long totalSuccessCountFromBegin;
private long totalElapsedTime;
private long activeVUserCountThisTime;
private long effectiveCount;
private ScriptBriefResultModel lastValidBriefResultModel;
private void setTotalFailCountThisTime(long totalFailCountThisTime) {
this.totalFailCountThisTime = totalFailCountThisTime;
}
private void setTotalSuccessCountThisTime(long totalSuccessCountThisTime) {
this.totalSuccessCountThisTime = totalSuccessCountThisTime;
}
private void setTotalSquareResponseTime(long totalSquareResponseTime) {
this.totalSquareResponseTime = totalSquareResponseTime;
}
private void setTotalFailThroughputThisTime(long totalFailThroughputThisTime) {
this.totalFailThroughputThisTime = totalFailThroughputThisTime;
}
private void setTotalSuccessThroughputThisTime(
long totalSuccessThroughputThisTime) {
this.totalSuccessThroughputThisTime = totalSuccessThroughputThisTime;
}
private void setMinResponseTimeThisTime(long minResponseTimeThisTime) {
this.minResponseTimeThisTime = minResponseTimeThisTime;
}
private void setMaxResponseTimeThisTime(long maxResponseTimeThisTime) {
this.maxResponseTimeThisTime = maxResponseTimeThisTime;
}
private void setTotalResponseTimeThisTime(long totalResponseTimeThisTime) {
this.totalResponseTimeThisTime = totalResponseTimeThisTime;
}
private void setTotalFailCountFromBegin(long totalFailCountFromBegin) {
this.totalFailCountFromBegin = totalFailCountFromBegin;
}
private void setTotalSuccessCoutFromBegin(long totalSuccessCoutFromBegin) {
this.totalSuccessCountFromBegin = totalSuccessCoutFromBegin;
}
private void setTotalElapsedTime(long totalElapsedTime) {
this.totalElapsedTime = totalElapsedTime;
}
private void setActiveVUserCountThisTime(long activeVUserCountThisTime) {
this.activeVUserCountThisTime = activeVUserCountThisTime;
}
private void setEffectiveCounte(long effetiveCount) {
this.effectiveCount = effetiveCount;
}
private ScriptBriefResultModel getLastValidBriefResultModel() {
return lastValidBriefResultModel;
}
private void setLastValidBriefResultModel(
ScriptBriefResultModel lastValidBriefResultModel) {
this.lastValidBriefResultModel = lastValidBriefResultModel;
}
public ScriptBriefStatistics() {
reset();
initLastValidBriefResultModel();
}
private void reset() {
this.setTotalFailCountFromBegin(0);
this.setTotalFailCountThisTime(0);
this.setTotalFailThroughputThisTime(0);
this.setTotalResponseTimeThisTime(0);
this.setTotalSquareResponseTime(0);
this.setTotalSuccessCountThisTime(0);
this.setTotalSuccessCoutFromBegin(0);
this.setTotalSuccessThroughputThisTime(0);
this.setTotalElapsedTime(0);
this.setEffectiveCounte(0);
this.setMaxResponseTimeThisTime(Long.MIN_VALUE);
this.setMinResponseTimeThisTime(Long.MAX_VALUE);
this.setActiveVUserCountThisTime(0);
}
private void initLastValidBriefResultModel() {
ScriptBriefResultModel initBriefModel = new ScriptBriefResultModel();
initBriefModel.setAverageElapsedTime(0);
initBriefModel.setAverageResponseTime(0);
initBriefModel.setFailRateThisTime(0);
initBriefModel.setFailThroughputThisTime(0);
initBriefModel.setFinished(false);
initBriefModel.setMaxResponseTime(0);
initBriefModel.setMinResponseTime(0);
initBriefModel.setPlanedRunningTime(0);
initBriefModel.setResponseTimeDeviationThisTime(0);
initBriefModel.setSuccessThroughputThisTime(0);
initBriefModel.setTotalFailCountFromBegin(0);
initBriefModel.setTotalSuccessCountFromBegin(0);
this.setLastValidBriefResultModel(initBriefModel);
}
public void add(DataStatisticsModel dataUnit) {
if (!(dataUnit instanceof AgentBriefStatusModel)) {
return;
}
add((AgentBriefStatusModel) dataUnit);
}
private void add(AgentBriefStatusModel briefModel) {
if (briefModel == null) {
return;
}
this.effectiveCount++;
if (briefModel.getMaxResponseTime() > this.maxResponseTimeThisTime) {
this.setMaxResponseTimeThisTime(briefModel.getMaxResponseTime());
}
if (briefModel.getMinResponseTime() < this.minResponseTimeThisTime) {
this.setMinResponseTimeThisTime(briefModel.getMinResponseTime());
}
this.totalFailCountFromBegin += briefModel.getFailCountFromBegin();
this.totalFailCountThisTime += briefModel.getFailCountThisTime();
this.totalFailThroughputThisTime += briefModel
.getFailThroughputThisTime();
this.totalResponseTimeThisTime += briefModel
.getTotalResponseTimeThisTime();
this.totalSquareResponseTime += briefModel
.getTotalSqureResponseTimeThisTime();
this.totalSuccessCountThisTime += briefModel.getSuccessCountThisTime();
this.totalSuccessCountFromBegin += briefModel
.getSuccessCountFromBegin();
this.totalSuccessThroughputThisTime += briefModel
.getSuccessThroughputThisTime();
this.activeVUserCountThisTime += briefModel.getvUserCount();
}
public ScriptBriefResultModel getStatistics() {
ScriptBriefResultModel result = new ScriptBriefResultModel();
long averageResponseTime = 0;
if (this.totalSuccessCountThisTime == 0) {
result.setAverageResponseTime(0);
result.setMaxResponseTime(0);
result.setMinResponseTime(0);
result.setResponseTimeDeviationThisTime(0);
if (this.totalFailCountThisTime == 0) {
result.setFailRateThisTime(0);
} else {
result.setFailRateThisTime(100);
}
} else {
averageResponseTime = this.totalResponseTimeThisTime
/ this.totalSuccessCountThisTime;
result.setAverageResponseTime(averageResponseTime);
result.setMaxResponseTime(this.maxResponseTimeThisTime);
result.setMinResponseTime(this.minResponseTimeThisTime);
result.setResponseTimeDeviationThisTime(Math.round(Math
.sqrt(this.totalSquareResponseTime
/ this.totalSuccessCountThisTime
- averageResponseTime * averageResponseTime)));
result.setFailRateThisTime(this.totalFailCountThisTime
* 100
/ (this.totalFailCountThisTime + this.totalSuccessCountThisTime));
}
result.setFailThroughputThisTime(this.totalFailThroughputThisTime);
result.setSuccessThroughputThisTime(this.totalSuccessThroughputThisTime);
result.setTotalFailCountFromBegin(this.totalFailCountFromBegin);
result.setTotalSuccessCountFromBegin(this.totalSuccessCountFromBegin);
if (this.effectiveCount == 0) {
result.setAverageElapsedTime(0);
} else {
result.setAverageElapsedTime(this.totalElapsedTime
/ this.effectiveCount);
}
result = dealWithInvalidSamplePoint(result);
result.setSamplingTime(new Date());
result.setvUserCount(this.activeVUserCountThisTime);
reset();
return result;
}
private ScriptBriefResultModel dealWithInvalidSamplePoint(
ScriptBriefResultModel inputModel) {
if (this.totalFailCountThisTime == 0
&& this.totalSuccessCountThisTime == 0) {
return this.getLastValidBriefResultModel();
}
this.setLastValidBriefResultModel(inputModel);
return inputModel;
}
}
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.Date;
import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel;
import org.bench4q.share.models.agent.statistics.DataStatisticsModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
public class ScriptBriefStatistics extends ScriptStatistics {
private long totalFailCountThisTime;
private long totalSuccessCountThisTime;
private long totalSquareResponseTime;
private long totalFailThroughputThisTime;
private long totalSuccessThroughputThisTime;
private long minResponseTimeThisTime;
private long maxResponseTimeThisTime;
private long totalResponseTimeThisTime;
private long totalFailCountFromBegin;
private long totalSuccessCountFromBegin;
private long totalElapsedTime;
private long activeVUserCountThisTime;
private long effectiveCount;
private ScriptBriefResultModel lastValidBriefResultModel;
private void setTotalFailCountThisTime(long totalFailCountThisTime) {
this.totalFailCountThisTime = totalFailCountThisTime;
}
private void setTotalSuccessCountThisTime(long totalSuccessCountThisTime) {
this.totalSuccessCountThisTime = totalSuccessCountThisTime;
}
private void setTotalSquareResponseTime(long totalSquareResponseTime) {
this.totalSquareResponseTime = totalSquareResponseTime;
}
private void setTotalFailThroughputThisTime(long totalFailThroughputThisTime) {
this.totalFailThroughputThisTime = totalFailThroughputThisTime;
}
private void setTotalSuccessThroughputThisTime(
long totalSuccessThroughputThisTime) {
this.totalSuccessThroughputThisTime = totalSuccessThroughputThisTime;
}
private void setMinResponseTimeThisTime(long minResponseTimeThisTime) {
this.minResponseTimeThisTime = minResponseTimeThisTime;
}
private void setMaxResponseTimeThisTime(long maxResponseTimeThisTime) {
this.maxResponseTimeThisTime = maxResponseTimeThisTime;
}
private void setTotalResponseTimeThisTime(long totalResponseTimeThisTime) {
this.totalResponseTimeThisTime = totalResponseTimeThisTime;
}
private void setTotalFailCountFromBegin(long totalFailCountFromBegin) {
this.totalFailCountFromBegin = totalFailCountFromBegin;
}
private void setTotalSuccessCoutFromBegin(long totalSuccessCoutFromBegin) {
this.totalSuccessCountFromBegin = totalSuccessCoutFromBegin;
}
private void setTotalElapsedTime(long totalElapsedTime) {
this.totalElapsedTime = totalElapsedTime;
}
private void setActiveVUserCountThisTime(long activeVUserCountThisTime) {
this.activeVUserCountThisTime = activeVUserCountThisTime;
}
private void setEffectiveCounte(long effetiveCount) {
this.effectiveCount = effetiveCount;
}
private ScriptBriefResultModel getLastValidBriefResultModel() {
return lastValidBriefResultModel;
}
private void setLastValidBriefResultModel(
ScriptBriefResultModel lastValidBriefResultModel) {
this.lastValidBriefResultModel = lastValidBriefResultModel;
}
public ScriptBriefStatistics() {
reset();
initLastValidBriefResultModel();
}
private void reset() {
this.setTotalFailCountFromBegin(0);
this.setTotalFailCountThisTime(0);
this.setTotalFailThroughputThisTime(0);
this.setTotalResponseTimeThisTime(0);
this.setTotalSquareResponseTime(0);
this.setTotalSuccessCountThisTime(0);
this.setTotalSuccessCoutFromBegin(0);
this.setTotalSuccessThroughputThisTime(0);
this.setTotalElapsedTime(0);
this.setEffectiveCounte(0);
this.setMaxResponseTimeThisTime(Long.MIN_VALUE);
this.setMinResponseTimeThisTime(Long.MAX_VALUE);
this.setActiveVUserCountThisTime(0);
}
private void initLastValidBriefResultModel() {
ScriptBriefResultModel initBriefModel = new ScriptBriefResultModel();
initBriefModel.setAverageElapsedTime(0);
initBriefModel.setAverageResponseTime(0);
initBriefModel.setFailRateThisTime(0);
initBriefModel.setFailThroughputThisTime(0);
initBriefModel.setFinished(false);
initBriefModel.setMaxResponseTime(0);
initBriefModel.setMinResponseTime(0);
initBriefModel.setPlanedRunningTime(0);
initBriefModel.setResponseTimeDeviationThisTime(0);
initBriefModel.setSuccessThroughputThisTime(0);
initBriefModel.setTotalFailCountFromBegin(0);
initBriefModel.setTotalSuccessCountFromBegin(0);
this.setLastValidBriefResultModel(initBriefModel);
}
public void add(DataStatisticsModel dataUnit) {
if (!(dataUnit instanceof AgentBriefStatusModel)) {
return;
}
add((AgentBriefStatusModel) dataUnit);
}
private void add(AgentBriefStatusModel briefModel) {
if (briefModel == null) {
return;
}
this.effectiveCount++;
if (briefModel.getMaxResponseTime() > this.maxResponseTimeThisTime) {
this.setMaxResponseTimeThisTime(briefModel.getMaxResponseTime());
}
if (briefModel.getMinResponseTime() < this.minResponseTimeThisTime) {
this.setMinResponseTimeThisTime(briefModel.getMinResponseTime());
}
this.totalFailCountFromBegin += briefModel.getFailCountFromBegin();
this.totalFailCountThisTime += briefModel.getFailCountThisTime();
this.totalFailThroughputThisTime += briefModel
.getFailThroughputThisTime();
this.totalResponseTimeThisTime += briefModel
.getTotalResponseTimeThisTime();
this.totalSquareResponseTime += briefModel
.getTotalSqureResponseTimeThisTime();
this.totalSuccessCountThisTime += briefModel.getSuccessCountThisTime();
this.totalSuccessCountFromBegin += briefModel
.getSuccessCountFromBegin();
this.totalSuccessThroughputThisTime += briefModel
.getSuccessThroughputThisTime();
this.activeVUserCountThisTime += briefModel.getvUserCount();
}
public ScriptBriefResultModel getStatistics() {
ScriptBriefResultModel result = new ScriptBriefResultModel();
long averageResponseTime = 0;
if (this.totalSuccessCountThisTime == 0) {
result.setAverageResponseTime(0);
result.setMaxResponseTime(0);
result.setMinResponseTime(0);
result.setResponseTimeDeviationThisTime(0);
if (this.totalFailCountThisTime == 0) {
result.setFailRateThisTime(0);
} else {
result.setFailRateThisTime(100);
}
} else {
averageResponseTime = this.totalResponseTimeThisTime
/ this.totalSuccessCountThisTime;
result.setAverageResponseTime(averageResponseTime);
result.setMaxResponseTime(this.maxResponseTimeThisTime);
result.setMinResponseTime(this.minResponseTimeThisTime);
result.setResponseTimeDeviationThisTime(Math.round(Math
.sqrt(this.totalSquareResponseTime
/ this.totalSuccessCountThisTime
- averageResponseTime * averageResponseTime)));
result.setFailRateThisTime(this.totalFailCountThisTime
* 100
/ (this.totalFailCountThisTime + this.totalSuccessCountThisTime));
}
result.setFailThroughputThisTime(this.totalFailThroughputThisTime);
result.setSuccessThroughputThisTime(this.totalSuccessThroughputThisTime);
result.setTotalFailCountFromBegin(this.totalFailCountFromBegin);
result.setTotalSuccessCountFromBegin(this.totalSuccessCountFromBegin);
if (this.effectiveCount == 0) {
result.setAverageElapsedTime(0);
} else {
result.setAverageElapsedTime(this.totalElapsedTime
/ this.effectiveCount);
}
result = dealWithInvalidSamplePoint(result);
result.setSamplingTime(new Date());
result.setvUserCount(this.activeVUserCountThisTime);
reset();
return result;
}
private ScriptBriefResultModel dealWithInvalidSamplePoint(
ScriptBriefResultModel inputModel) {
if (this.totalFailCountThisTime == 0
&& this.totalSuccessCountThisTime == 0) {
return this.getLastValidBriefResultModel();
}
this.setLastValidBriefResultModel(inputModel);
return inputModel;
}
}

View File

@ -1,13 +1,13 @@
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.Date;
import org.bench4q.share.models.master.statistics.SampleModel;
public abstract class ScriptStatistics implements DataStatistics {
protected void makeUpResultModelWithSamplingTime(
SampleModel resultModel) {
resultModel.setSamplingTime(new Date());
}
}
package org.bench4q.master.domain.valueobject.datastatistics;
import java.util.Date;
import org.bench4q.share.models.master.statistics.SampleModel;
public abstract class ScriptStatistics implements DataStatistics {
protected void makeUpResultModelWithSamplingTime(
SampleModel resultModel) {
resultModel.setSamplingTime(new Date());
}
}

View File

@ -1,25 +1,25 @@
package org.bench4q.master.domain.valueobject.datastatistics;
import org.bench4q.master.infrastructure.communication.MonitorMessenger;
import org.bench4q.share.models.monitor.MonitorMain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TestMonitorSampler {
private MonitorMessenger monitorMessenger;
@Autowired
private void setMonitorMessenger(MonitorMessenger monitorMessenger) {
this.monitorMessenger = monitorMessenger;
}
public MonitorMain getMonitorResult( String hostName,
int port) {
return this.monitorMessenger
.monitorModel(hostName, port);
}
}
package org.bench4q.master.domain.valueobject.datastatistics;
import org.bench4q.master.infrastructure.communication.MonitorMessenger;
import org.bench4q.share.models.monitor.MonitorMain;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TestMonitorSampler {
private MonitorMessenger monitorMessenger;
@Autowired
private void setMonitorMessenger(MonitorMessenger monitorMessenger) {
this.monitorMessenger = monitorMessenger;
}
public MonitorMain getMonitorResult( String hostName,
int port) {
return this.monitorMessenger
.monitorModel(hostName, port);
}
}

View File

@ -1,7 +1,7 @@
package org.bench4q.master.domain.valueobject.schedulscript;
import java.util.UUID;
public interface TaskCompleteCallback {
void doTaskComplete(UUID testPlanID);
}
package org.bench4q.master.domain.valueobject.schedulscript;
import java.util.UUID;
public interface TaskCompleteCallback {
void doTaskComplete(UUID testPlanID);
}

View File

@ -1,41 +1,41 @@
package org.bench4q.master.domain.valueobject.schedulscript;
import java.util.TimerTask;
import org.bench4q.master.domain.RunningScriptInterface;
import org.bench4q.master.domain.service.AgentService;
import org.bench4q.master.helper.ApplicationContextHelper;
public class WarmUpOverTask extends TimerTask {
private AgentService agentService;
private RunningScriptInterface runningScript;
public AgentService getAgentService() {
return agentService;
}
public void setAgentService(AgentService agentService) {
this.agentService = agentService;
}
public RunningScriptInterface getRunningScript() {
return runningScript;
}
public void setRunningScript(RunningScriptInterface runningScript) {
this.runningScript = runningScript;
}
public WarmUpOverTask() {
this.setAgentService(ApplicationContextHelper.getContext().getBean(
AgentService.class));
}
@Override
public void run() {
System.out.println("warm up over and start to execute!");
if (this.getRunningScript() == null) {
return;
}
}
}
package org.bench4q.master.domain.valueobject.schedulscript;
import java.util.TimerTask;
import org.bench4q.master.domain.RunningScriptInterface;
import org.bench4q.master.domain.service.AgentService;
import org.bench4q.master.helper.ApplicationContextHelper;
public class WarmUpOverTask extends TimerTask {
private AgentService agentService;
private RunningScriptInterface runningScript;
public AgentService getAgentService() {
return agentService;
}
public void setAgentService(AgentService agentService) {
this.agentService = agentService;
}
public RunningScriptInterface getRunningScript() {
return runningScript;
}
public void setRunningScript(RunningScriptInterface runningScript) {
this.runningScript = runningScript;
}
public WarmUpOverTask() {
this.setAgentService(ApplicationContextHelper.getContext().getBean(
AgentService.class));
}
@Override
public void run() {
System.out.println("warm up over and start to execute!");
if (this.getRunningScript() == null) {
return;
}
}
}

View File

@ -1,7 +1,7 @@
package org.bench4q.master.domain.valueobject.transaction;
public interface Transaction {
public Object execute() throws Exception;
public void rollBack();
}
package org.bench4q.master.domain.valueobject.transaction;
public interface Transaction {
public Object execute() throws Exception;
public void rollBack();
}

View File

@ -1,20 +1,20 @@
package org.bench4q.master.domain.valueobject.transaction.exception;
public class AgentRunException extends Exception {
/**
* To make running agent with a scenario a transaction when throw this
* exception, I can roll back it.
*/
private static final long serialVersionUID = 2788339373490137449L;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
package org.bench4q.master.domain.valueobject.transaction.exception;
public class AgentRunException extends Exception {
/**
* To make running agent with a scenario a transaction when throw this
* exception, I can roll back it.
*/
private static final long serialVersionUID = 2788339373490137449L;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}

View File

@ -1,18 +1,18 @@
package org.bench4q.master.domain.valueobject.transaction.exception;
public class ScriptLoadDistributeException extends Exception {
private static final long serialVersionUID = -5230579598325900610L;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ScriptLoadDistributeException() {
this.setMessage("Distribute load for script fails!");
}
}
package org.bench4q.master.domain.valueobject.transaction.exception;
public class ScriptLoadDistributeException extends Exception {
private static final long serialVersionUID = -5230579598325900610L;
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public ScriptLoadDistributeException() {
this.setMessage("Distribute load for script fails!");
}
}

View File

@ -1,13 +1,13 @@
package org.bench4q.master.domain.valueobject.transaction.impl;
import org.bench4q.master.domain.valueobject.transaction.Transaction;
public class TestPlanDistribute implements Transaction {
public Object execute() {
return null;
}
public void rollBack() {
}
}
package org.bench4q.master.domain.valueobject.transaction.impl;
import org.bench4q.master.domain.valueobject.transaction.Transaction;
public class TestPlanDistribute implements Transaction {
public Object execute() {
return null;
}
public void rollBack() {
}
}

View File

@ -1,47 +1,47 @@
package org.bench4q.master.exception;
/**
* To deal with the response of each function of TestPlanController
*
* @author coderfengyun
*
*/
public class Bench4QException extends Exception {
/**
*
*/
private static final long serialVersionUID = 7450550491330737876L;
private String code;
private String message;
private String resource;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public Bench4QException(String code, String message, String resource) {
this.setCode(code);
this.setMessage(message);
this.setResource(resource);
}
}
package org.bench4q.master.exception;
/**
* To deal with the response of each function of TestPlanController
*
* @author coderfengyun
*
*/
public class Bench4QException extends Exception {
/**
*
*/
private static final long serialVersionUID = 7450550491330737876L;
private String code;
private String message;
private String resource;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getResource() {
return resource;
}
public void setResource(String resource) {
this.resource = resource;
}
public Bench4QException(String code, String message, String resource) {
this.setCode(code);
this.setMessage(message);
this.setResource(resource);
}
}

View File

@ -1,19 +1,19 @@
package org.bench4q.master.exception;
import org.bench4q.share.models.ErrorResponseModel;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Component
public class Bench4QExceptionSweeper {
@ExceptionHandler(Bench4QException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponseModel handleException(Bench4QException e) {
return ErrorResponseModel.buildErrorResponse(e.getCode(),
e.getMessage(), e.getResource());
}
}
package org.bench4q.master.exception;
import org.bench4q.share.models.ErrorResponseModel;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
@Component
public class Bench4QExceptionSweeper {
@ExceptionHandler(Bench4QException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponseModel handleException(Bench4QException e) {
return ErrorResponseModel.buildErrorResponse(e.getCode(),
e.getMessage(), e.getResource());
}
}

View File

@ -1,13 +1,13 @@
package org.bench4q.master.exception;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class ExceptionLog {
public static ByteArrayOutputStream getStackTrace(Throwable e) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(outputStream);
e.printStackTrace(printStream);
return outputStream;
}
}
package org.bench4q.master.exception;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
public class ExceptionLog {
public static ByteArrayOutputStream getStackTrace(Throwable e) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
PrintStream printStream = new PrintStream(outputStream);
e.printStackTrace(printStream);
return outputStream;
}
}

View File

@ -1,73 +1,73 @@
package org.bench4q.master.exception;
/**
*
* @author coderfengyun
*
*/
public class ExceptionUtils {
public static class EntityUniqueAlReadyExistException extends Exception {
private static final long serialVersionUID = 8666833843441862022L;
private String msg;
private String getMsg() {
return msg;
}
private void setMsg(String msg) {
this.msg = msg;
}
public EntityUniqueAlReadyExistException(String message) {
this.setMsg(message);
}
@Override
public String getMessage() {
return this.getMsg();
}
}
public static class UserAlreadyExistException extends Exception {
private static final long serialVersionUID = -5465994901904292643L;
@Override
public String getMessage() {
return "The User Already exists!";
}
}
public static class MultiUserWithSameUserNameExist extends Exception {
private static final long serialVersionUID = 1L;
@Override
public String getMessage() {
return "Multi users exist with the same userName!";
}
}
public static class TransactionCommitException extends Exception {
private static final long serialVersionUID = -6104657204412644717L;
@Override
public String getMessage() {
return "Transaction commit fails!";
}
}
public static class IllegalParameterException extends Exception {
private static final long serialVersionUID = -4999157899142651582L;
private String msg;
public IllegalParameterException(String msg) {
this.msg = msg;
}
@Override
public String getMessage() {
return this.msg;
}
}
}
package org.bench4q.master.exception;
/**
*
* @author coderfengyun
*
*/
public class ExceptionUtils {
public static class EntityUniqueAlReadyExistException extends Exception {
private static final long serialVersionUID = 8666833843441862022L;
private String msg;
private String getMsg() {
return msg;
}
private void setMsg(String msg) {
this.msg = msg;
}
public EntityUniqueAlReadyExistException(String message) {
this.setMsg(message);
}
@Override
public String getMessage() {
return this.getMsg();
}
}
public static class UserAlreadyExistException extends Exception {
private static final long serialVersionUID = -5465994901904292643L;
@Override
public String getMessage() {
return "The User Already exists!";
}
}
public static class MultiUserWithSameUserNameExist extends Exception {
private static final long serialVersionUID = 1L;
@Override
public String getMessage() {
return "Multi users exist with the same userName!";
}
}
public static class TransactionCommitException extends Exception {
private static final long serialVersionUID = -6104657204412644717L;
@Override
public String getMessage() {
return "Transaction commit fails!";
}
}
public static class IllegalParameterException extends Exception {
private static final long serialVersionUID = -4999157899142651582L;
private String msg;
public IllegalParameterException(String msg) {
this.msg = msg;
}
@Override
public String getMessage() {
return this.msg;
}
}
}

View File

@ -1,24 +1,24 @@
package org.bench4q.master.helper;
import java.util.List;
import org.bench4q.master.domain.EntityBase;
public class CollectionHelper {
/**
*
* @param container
* @param id
* @return null if not exists
*/
public static <T extends EntityBase, ID> T tryGetItemById(
List<T> container, ID id) {
for (T item : container) {
if (id.toString().equals(item.extractIdentifier().toString())) {
return item;
}
}
return null;
}
}
package org.bench4q.master.helper;
import java.util.List;
import org.bench4q.master.domain.EntityBase;
public class CollectionHelper {
/**
*
* @param container
* @param id
* @return null if not exists
*/
public static <T extends EntityBase, ID> T tryGetItemById(
List<T> container, ID id) {
for (T item : container) {
if (id.toString().equals(item.extractIdentifier().toString())) {
return item;
}
}
return null;
}
}

View File

@ -1,33 +1,33 @@
package org.bench4q.master.helper;
import java.security.MessageDigest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class HashHelper {
private StringHelper stringHelper;
private StringHelper getStringHelper() {
return stringHelper;
}
@Autowired
private void setStringHelper(StringHelper stringHelper) {
this.stringHelper = stringHelper;
}
public String sha1Hash(String source) {
try {
String ret = new String(source);
MessageDigest md = MessageDigest.getInstance("SHA-1");
ret = this.getStringHelper().convertToHexString(
md.digest(ret.getBytes()));
return ret;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
package org.bench4q.master.helper;
import java.security.MessageDigest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class HashHelper {
private StringHelper stringHelper;
private StringHelper getStringHelper() {
return stringHelper;
}
@Autowired
private void setStringHelper(StringHelper stringHelper) {
this.stringHelper = stringHelper;
}
public String sha1Hash(String source) {
try {
String ret = new String(source);
MessageDigest md = MessageDigest.getInstance("SHA-1");
ret = this.getStringHelper().convertToHexString(
md.digest(ret.getBytes()));
return ret;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -1,36 +1,36 @@
package org.bench4q.master.helper;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.springframework.stereotype.Component;
@Component
public final class SessionHelper {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionHelper() {
try {
Configuration cfg = new Configuration()
.configure("org/bench4q/master/config/hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
this.setSessionFactory(cfg.buildSessionFactory(serviceRegistry));
} catch (Exception e) {
e.printStackTrace();
}
}
public Session openSession() {
return this.getSessionFactory().openSession();
}
}
package org.bench4q.master.helper;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.springframework.stereotype.Component;
@Component
public final class SessionHelper {
private SessionFactory sessionFactory;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public SessionHelper() {
try {
Configuration cfg = new Configuration()
.configure("org/bench4q/master/config/hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
this.setSessionFactory(cfg.buildSessionFactory(serviceRegistry));
} catch (Exception e) {
e.printStackTrace();
}
}
public Session openSession() {
return this.getSessionFactory().openSession();
}
}

View File

@ -1,38 +1,38 @@
package org.bench4q.master.helper;
import org.springframework.stereotype.Component;
@Component
public final class StringHelper {
public String convertToHexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex;
}
return ret;
}
private byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
public byte[] convertToBytes(String src) {
byte[] ret = new byte[src.getBytes().length / 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < ret.length; i++) {
ret[i] = this.uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
}
package org.bench4q.master.helper;
import org.springframework.stereotype.Component;
@Component
public final class StringHelper {
public String convertToHexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex;
}
return ret;
}
private byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 }))
.byteValue();
_b0 = (byte) (_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 }))
.byteValue();
byte ret = (byte) (_b0 ^ _b1);
return ret;
}
public byte[] convertToBytes(String src) {
byte[] ret = new byte[src.getBytes().length / 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < ret.length; i++) {
ret[i] = this.uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
}

View File

@ -1,112 +1,112 @@
package org.bench4q.master.infrastructure.communication;
import java.io.IOException;
import java.util.Date;
import javax.xml.bind.JAXBException;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.service.MonitorResultService;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.share.communication.HttpRequester;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.statistics.SampleModel;
import org.bench4q.share.models.monitor.MonitorMain;
import org.bench4q.share.models.monitor.MemoryModel;
import org.bench4q.share.models.monitor.NetworkInterfaceModel;
import org.bench4q.share.models.monitor.PhysicalDiskModel;
import org.bench4q.share.models.monitor.ProcessModel;
import org.bench4q.share.models.monitor.ProcessorModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MonitorMessenger {
private HttpRequester httpRequester;
private MonitorResultService monitorResultService;
private Logger logger = Logger.getLogger(MonitorMessenger.class);
public HttpRequester getHttpRequester() {
return httpRequester;
}
@Autowired
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
public MonitorResultService getMonitorResultService() {
return monitorResultService;
}
@Autowired
public void setMonitorResultService(
MonitorResultService monitorResultService) {
this.monitorResultService = monitorResultService;
}
private String buildUrl(String hostName, int port, String relativePath) {
return hostName + ":" + port + relativePath;
}
public PhysicalDiskModel physicalDisk(String hostName, int port) {
return getMonitorModel(hostName, port, PhysicalDiskModel.class,
"physicalDisk");
}
private <T extends SampleModel> T getMonitorModel(String hostName,
int port, Class<T> resultClass, String monitorTarget) {
try {
Date sampleDate = new Date();
HttpResponse httpResponse = this.getHttpRequester().sendGet(
buildUrl(hostName, port, "/monitor/" + monitorTarget),
null, null);
if (HttpRequester.isInvalidResponse(httpResponse)) {
logger.info("The httpResponse is invalid ");
return null;
}
@SuppressWarnings("unchecked")
T model = (T) MarshalHelper.unmarshal(resultClass,
httpResponse.getContent());
model.setSamplingTime(sampleDate);
return model;
} catch (IOException e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
} catch (JAXBException e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
}
public MemoryModel memory(String hostName, int port) {
return getMonitorModel(hostName, port, MemoryModel.class, "memory");
}
public ProcessorModel processor(String hostName, int port) {
return this.getMonitorModel(hostName, port, ProcessorModel.class,
"processor");
}
public NetworkInterfaceModel networkInterface(String hostName, int port) {
return this.getMonitorModel(hostName, port,
NetworkInterfaceModel.class, "network");
}
public ProcessModel process(String hostName, int port) {
return this.getMonitorModel(hostName, port, ProcessModel.class,
"process");
}
public MonitorMain monitorModel(String hostName, int port) {
return this.getMonitorModel(hostName, port, MonitorMain.class, "all");
}
}
package org.bench4q.master.infrastructure.communication;
import java.io.IOException;
import java.util.Date;
import javax.xml.bind.JAXBException;
import org.apache.log4j.Logger;
import org.bench4q.master.domain.service.MonitorResultService;
import org.bench4q.master.exception.ExceptionLog;
import org.bench4q.share.communication.HttpRequester;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.statistics.SampleModel;
import org.bench4q.share.models.monitor.MonitorMain;
import org.bench4q.share.models.monitor.MemoryModel;
import org.bench4q.share.models.monitor.NetworkInterfaceModel;
import org.bench4q.share.models.monitor.PhysicalDiskModel;
import org.bench4q.share.models.monitor.ProcessModel;
import org.bench4q.share.models.monitor.ProcessorModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class MonitorMessenger {
private HttpRequester httpRequester;
private MonitorResultService monitorResultService;
private Logger logger = Logger.getLogger(MonitorMessenger.class);
public HttpRequester getHttpRequester() {
return httpRequester;
}
@Autowired
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
public MonitorResultService getMonitorResultService() {
return monitorResultService;
}
@Autowired
public void setMonitorResultService(
MonitorResultService monitorResultService) {
this.monitorResultService = monitorResultService;
}
private String buildUrl(String hostName, int port, String relativePath) {
return hostName + ":" + port + relativePath;
}
public PhysicalDiskModel physicalDisk(String hostName, int port) {
return getMonitorModel(hostName, port, PhysicalDiskModel.class,
"physicalDisk");
}
private <T extends SampleModel> T getMonitorModel(String hostName,
int port, Class<T> resultClass, String monitorTarget) {
try {
Date sampleDate = new Date();
HttpResponse httpResponse = this.getHttpRequester().sendGet(
buildUrl(hostName, port, "/monitor/" + monitorTarget),
null, null);
if (HttpRequester.isInvalidResponse(httpResponse)) {
logger.info("The httpResponse is invalid ");
return null;
}
@SuppressWarnings("unchecked")
T model = (T) MarshalHelper.unmarshal(resultClass,
httpResponse.getContent());
model.setSamplingTime(sampleDate);
return model;
} catch (IOException e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
} catch (JAXBException e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
catch (Exception e) {
logger.error(ExceptionLog.getStackTrace(e));
return null;
}
}
public MemoryModel memory(String hostName, int port) {
return getMonitorModel(hostName, port, MemoryModel.class, "memory");
}
public ProcessorModel processor(String hostName, int port) {
return this.getMonitorModel(hostName, port, ProcessorModel.class,
"processor");
}
public NetworkInterfaceModel networkInterface(String hostName, int port) {
return this.getMonitorModel(hostName, port,
NetworkInterfaceModel.class, "network");
}
public ProcessModel process(String hostName, int port) {
return this.getMonitorModel(hostName, port, ProcessModel.class,
"process");
}
public MonitorMain monitorModel(String hostName, int port) {
return this.getMonitorModel(hostName, port, MonitorMain.class, "all");
}
}

View File

@ -1,5 +1,5 @@
package org.bench4q.master.infrastructure.highavailable;
public interface CurrentLoadObserver {
public void executePendingTestPlan();
}
package org.bench4q.master.infrastructure.highavailable;
public interface CurrentLoadObserver {
public void executePendingTestPlan();
}

View File

@ -1,17 +1,17 @@
package org.bench4q.master.infrastructure.highavailable;
public class CurrentLoadSubject {
private CurrentLoadObserver observer;
public CurrentLoadObserver getObserver() {
return observer;
}
public void setObserver(CurrentLoadObserver observer) {
this.observer = observer;
}
public void notifyOberser() {
this.getObserver().executePendingTestPlan();
}
}
package org.bench4q.master.infrastructure.highavailable;
public class CurrentLoadSubject {
private CurrentLoadObserver observer;
public CurrentLoadObserver getObserver() {
return observer;
}
public void setObserver(CurrentLoadObserver observer) {
this.observer = observer;
}
public void notifyOberser() {
this.getObserver().executePendingTestPlan();
}
}

View File

@ -1,31 +1,31 @@
log4j.rootLogger = INFO,WARN,ERROR,FALTAL,D
log4j.appender.WARN = org.apache.log4j.DailyRollingFileAppender
log4j.appender.WARN.File = logs/warnlog.log
log4j.appender.WARN.Append = true
log4j.appender.WARN.Threshold = WARN
log4j.appender.WARN.layout = org.apache.log4j.PatternLayout
log4j.appender.WARN.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender
log4j.appender.ERROR.File = logs/errorlog.log
log4j.appender.ERROR.Append = true
log4j.appender.ERROR.Threshold = ERROR
log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout
log4j.appender.ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.FALTAL = org.apache.log4j.DailyRollingFileAppender
log4j.appender.FALTAL.File = logs/faltallog.log
log4j.appender.FALTAL.Append = true
log4j.appender.FALTAL.Threshold = ERROR
log4j.appender.FALTAL.layout = org.apache.log4j.PatternLayout
log4j.appender.FALTAL.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = TRACE
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.rootLogger = INFO,WARN,ERROR,FALTAL,D
log4j.appender.WARN = org.apache.log4j.DailyRollingFileAppender
log4j.appender.WARN.File = logs/warnlog.log
log4j.appender.WARN.Append = true
log4j.appender.WARN.Threshold = WARN
log4j.appender.WARN.layout = org.apache.log4j.PatternLayout
log4j.appender.WARN.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender
log4j.appender.ERROR.File = logs/errorlog.log
log4j.appender.ERROR.Append = true
log4j.appender.ERROR.Threshold = ERROR
log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout
log4j.appender.ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.FALTAL = org.apache.log4j.DailyRollingFileAppender
log4j.appender.FALTAL.File = logs/faltallog.log
log4j.appender.FALTAL.Append = true
log4j.appender.FALTAL.Threshold = ERROR
log4j.appender.FALTAL.layout = org.apache.log4j.PatternLayout
log4j.appender.FALTAL.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = TRACE
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n

View File

@ -1,6 +1,6 @@
portToServe=7979
pickTestPlanCycleInSeconds=60
maxFailTime=10
minExcuteIntervalInSeconds=600
minSampleCycleInSeconds=10
portToServe=7979
pickTestPlanCycleInSeconds=60
maxFailTime=10
minExcuteIntervalInSeconds=600
minSampleCycleInSeconds=10
scriptParamRootFolder=ScriptParameterization

View File

@ -1,19 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:component-scan base-package="org.bench4q" />
<mvc:annotation-driven />
<task:annotation-driven />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000" />
<property name="maxInMemorySize" value="5000000" />
</bean>
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:component-scan base-package="org.bench4q" />
<mvc:annotation-driven />
<task:annotation-driven />
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000" />
<property name="maxInMemorySize" value="5000000" />
</bean>
</beans>

View File

@ -1,47 +1,47 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver </property>
<property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/bench4q_master
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456 </property>
<property name="hibernate.connection.pool.size">20 </property>
<property name="hibernate.show_sql">false</property>
<property name="format_sql">false</property>
<property name="Connection.useUnicode">true </property>
<property name="connection.characterEncoding">utf-8 </property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect </property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="connection.autoReconnect">true</property>
<property name="connection.autoReconnectForPools">true</property>
<property name="connection.is-connection-validation-required">true</property>
<mapping class="org.bench4q.master.domain.entity.User" />
<mapping class="org.bench4q.master.domain.entity.Script" />
<mapping class="org.bench4q.master.domain.entity.PlanedConfig" />
<mapping class="org.bench4q.master.domain.entity.Agent" />
<mapping class="org.bench4q.master.domain.entity.Port" />
<mapping class="org.bench4q.master.domain.entity.TestPlan" />
<mapping class="org.bench4q.master.domain.entity.TestPlanScript" />
<mapping class="org.bench4q.master.domain.entity.RunningAgentDB" />
<mapping class="org.bench4q.master.domain.entity.TestPlanScriptResult" />
<mapping class="org.bench4q.master.domain.entity.Monitor" />
<mapping class="org.bench4q.master.domain.entity.MonitorResult" />
<mapping class="org.bench4q.master.domain.entity.plugin.PluginUI" />
<mapping class="org.bench4q.master.domain.entity.plugin.PluginInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.BehaviorInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.ParamType" />
<mapping class="org.bench4q.master.domain.entity.plugin.PluginParamInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.BehaviorParamInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.ParamInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.FieldType" />
<mapping class="org.bench4q.master.domain.entity.plugin.NFieldType" />
<mapping class="org.bench4q.master.domain.entity.plugin.CheckBoxType" />
<mapping class="org.bench4q.master.domain.entity.plugin.TableType" />
<mapping class="org.bench4q.master.domain.entity.plugin.RadioButtonType" />
<mapping class="org.bench4q.master.domain.entity.plugin.ComboType" />
<mapping class="org.bench4q.master.domain.entity.plugin.ChoiceType" />
<mapping class="org.bench4q.master.domain.entity.plugin.FileType" />
</session-factory>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver </property>
<property name="hibernate.connection.url"> jdbc:mysql://localhost:3306/bench4q_master
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">123456 </property>
<property name="hibernate.connection.pool.size">20 </property>
<property name="hibernate.show_sql">false</property>
<property name="format_sql">false</property>
<property name="Connection.useUnicode">true </property>
<property name="connection.characterEncoding">utf-8 </property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect </property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="connection.autoReconnect">true</property>
<property name="connection.autoReconnectForPools">true</property>
<property name="connection.is-connection-validation-required">true</property>
<mapping class="org.bench4q.master.domain.entity.User" />
<mapping class="org.bench4q.master.domain.entity.Script" />
<mapping class="org.bench4q.master.domain.entity.PlanedConfig" />
<mapping class="org.bench4q.master.domain.entity.Agent" />
<mapping class="org.bench4q.master.domain.entity.Port" />
<mapping class="org.bench4q.master.domain.entity.TestPlan" />
<mapping class="org.bench4q.master.domain.entity.TestPlanScript" />
<mapping class="org.bench4q.master.domain.entity.RunningAgentDB" />
<mapping class="org.bench4q.master.domain.entity.TestPlanScriptResult" />
<mapping class="org.bench4q.master.domain.entity.Monitor" />
<mapping class="org.bench4q.master.domain.entity.MonitorResult" />
<mapping class="org.bench4q.master.domain.entity.plugin.PluginUI" />
<mapping class="org.bench4q.master.domain.entity.plugin.PluginInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.BehaviorInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.ParamType" />
<mapping class="org.bench4q.master.domain.entity.plugin.PluginParamInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.BehaviorParamInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.ParamInfo" />
<mapping class="org.bench4q.master.domain.entity.plugin.FieldType" />
<mapping class="org.bench4q.master.domain.entity.plugin.NFieldType" />
<mapping class="org.bench4q.master.domain.entity.plugin.CheckBoxType" />
<mapping class="org.bench4q.master.domain.entity.plugin.TableType" />
<mapping class="org.bench4q.master.domain.entity.plugin.RadioButtonType" />
<mapping class="org.bench4q.master.domain.entity.plugin.ComboType" />
<mapping class="org.bench4q.master.domain.entity.plugin.ChoiceType" />
<mapping class="org.bench4q.master.domain.entity.plugin.FileType" />
</session-factory>
</hibernate-configuration>

View File

@ -1,54 +1,54 @@
# This file specifies configuration for maxq.
# Names of generator classes to make available in the GUI. We do not
# include the Java generator here by default because MaxQ cannot run
# these scripts, only generate them. We do not include SampleGenerator
# because it is only of interest to people writing new generators and
# might confuse regular MaxQ users.
#
# Class names are separated by colons.
generator.classnames=com.bitmechanic.maxq.generator.IsacCodeGenerator
# What port MaxQ should listen on for requests from the browser. Default is
# port 8090.
local.proxy.port=8090
# HTTP proxy settings for MaxQ's own requests; MaxQ can operate behind a
# firewall.
#remote.proxy.host=myproxy
#remote.proxy.port=3128
##########################################
# properties used in TemplateCodeGenerator
##########################################
template.theme=HttpUnit
##########################################
# properties used in IsacCodeGenerator
##########################################
#for constant think times
generator.isac.timer=ConstantTimer
#not to capture think times
#generator.isac.timer=null
#for randomized think times
#generator.isac.timer=Random
#extra properties for a uniform distribution
#generator.isac.timer.random.dist=uniform
#generator.isac.timer.random.delta=1000
#extra properties for a gaussian distribution
#generator.isac.timer.random.dist=gaussian
#generator.isac.timer.random.delta=1000
#generator.isac.timer.random.deviation=10
#extra properties for a Poisson law distribution
#generator.isac.timer.random.dist=poisson
#generator.isac.timer.random.unit=1
#extra properties for a negative exponential law distribution
#generator.isac.timer.random.dist=negexpo
# This file specifies configuration for maxq.
# Names of generator classes to make available in the GUI. We do not
# include the Java generator here by default because MaxQ cannot run
# these scripts, only generate them. We do not include SampleGenerator
# because it is only of interest to people writing new generators and
# might confuse regular MaxQ users.
#
# Class names are separated by colons.
generator.classnames=com.bitmechanic.maxq.generator.IsacCodeGenerator
# What port MaxQ should listen on for requests from the browser. Default is
# port 8090.
local.proxy.port=8090
# HTTP proxy settings for MaxQ's own requests; MaxQ can operate behind a
# firewall.
#remote.proxy.host=myproxy
#remote.proxy.port=3128
##########################################
# properties used in TemplateCodeGenerator
##########################################
template.theme=HttpUnit
##########################################
# properties used in IsacCodeGenerator
##########################################
#for constant think times
generator.isac.timer=ConstantTimer
#not to capture think times
#generator.isac.timer=null
#for randomized think times
#generator.isac.timer=Random
#extra properties for a uniform distribution
#generator.isac.timer.random.dist=uniform
#generator.isac.timer.random.delta=1000
#extra properties for a gaussian distribution
#generator.isac.timer.random.dist=gaussian
#generator.isac.timer.random.delta=1000
#generator.isac.timer.random.deviation=10
#extra properties for a Poisson law distribution
#generator.isac.timer.random.dist=poisson
#generator.isac.timer.random.unit=1
#extra properties for a negative exponential law distribution
#generator.isac.timer.random.dist=negexpo
#generator.isac.timer.random.delta=10

View File

@ -1,44 +1,44 @@
package ModelTest;
import java.util.ArrayList;
import java.util.List;
import org.bench4q.share.models.agent.ParameterModel;
import org.bench4q.share.models.agent.scriptrecord.BehaviorModel;
import org.junit.Test;
import static org.junit.Assert.*;
public class BehaviorBaseModelTest {
@Test
public void testUserBehavior() {
List<ParameterModel> parameterModels = new ArrayList<ParameterModel>();
ParameterModel param = new ParameterModel();
param.setKey("url");
param.setValue("www.baidu.com");
parameterModels.add(param);
BehaviorModel behaviorBaseModel = BehaviorModel
.UserBehaviorBuilder(20, "Put", "http", parameterModels);
assertEquals(20, behaviorBaseModel.getId());
assertEquals("Put", behaviorBaseModel.getName());
assertEquals("http", behaviorBaseModel.getUse());
assertEquals("USERBEHAVIOR", behaviorBaseModel.getType());
assertEquals(1, behaviorBaseModel.getParameters().size());
}
@Test
public void testTimerBehavior() {
List<ParameterModel> params = new ArrayList<ParameterModel>();
ParameterModel param = new ParameterModel();
param.setKey("Time");
param.setValue("209");
params.add(param);
BehaviorModel behaviorBaseModel = BehaviorModel
.TimerBehaviorBuilder(3, "Sleep", "ContantTimer", params);
assertEquals(3, behaviorBaseModel.getId());
assertEquals("Sleep", behaviorBaseModel.getName());
assertEquals("ContantTimer", behaviorBaseModel.getUse());
assertEquals(1, behaviorBaseModel.getParameters().size());
assertEquals("TIMERBEHAVIOR", behaviorBaseModel.getType());
}
}
package ModelTest;
import java.util.ArrayList;
import java.util.List;
import org.bench4q.share.models.agent.ParameterModel;
import org.bench4q.share.models.agent.scriptrecord.BehaviorModel;
import org.junit.Test;
import static org.junit.Assert.*;
public class BehaviorBaseModelTest {
@Test
public void testUserBehavior() {
List<ParameterModel> parameterModels = new ArrayList<ParameterModel>();
ParameterModel param = new ParameterModel();
param.setKey("url");
param.setValue("www.baidu.com");
parameterModels.add(param);
BehaviorModel behaviorBaseModel = BehaviorModel
.UserBehaviorBuilder(20, "Put", "http", parameterModels);
assertEquals(20, behaviorBaseModel.getId());
assertEquals("Put", behaviorBaseModel.getName());
assertEquals("http", behaviorBaseModel.getUse());
assertEquals("USERBEHAVIOR", behaviorBaseModel.getType());
assertEquals(1, behaviorBaseModel.getParameters().size());
}
@Test
public void testTimerBehavior() {
List<ParameterModel> params = new ArrayList<ParameterModel>();
ParameterModel param = new ParameterModel();
param.setKey("Time");
param.setValue("209");
params.add(param);
BehaviorModel behaviorBaseModel = BehaviorModel
.TimerBehaviorBuilder(3, "Sleep", "ContantTimer", params);
assertEquals(3, behaviorBaseModel.getId());
assertEquals("Sleep", behaviorBaseModel.getName());
assertEquals("ContantTimer", behaviorBaseModel.getUse());
assertEquals(1, behaviorBaseModel.getParameters().size());
assertEquals("TIMERBEHAVIOR", behaviorBaseModel.getType());
}
}

View File

@ -1,35 +1,35 @@
package ModelTest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.junit.Test;
import static org.junit.Assert.*;
public class IpTest {
@Test
public void testIp() throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr.getHostAddress().toString());
System.out.println(new SimpleDateFormat("yyyyMMdd").format(new Date()));
}
@Test
public void testClassName() throws ClassNotFoundException {
ScriptBriefResultModel model = new ScriptBriefResultModel();
System.out.println(model.getClass().getName());
assertTrue(Class.forName(model.getClass().getName()).equals(
model.getClass()));
}
@Test
public void testForInheritance() throws ClassNotFoundException {
Object model = new ScriptBriefResultModel();
assertEquals(ScriptBriefResultModel.class.getName(), model.getClass()
.getName());
}
}
package ModelTest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.junit.Test;
import static org.junit.Assert.*;
public class IpTest {
@Test
public void testIp() throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
System.out.println(addr.getHostAddress().toString());
System.out.println(new SimpleDateFormat("yyyyMMdd").format(new Date()));
}
@Test
public void testClassName() throws ClassNotFoundException {
ScriptBriefResultModel model = new ScriptBriefResultModel();
System.out.println(model.getClass().getName());
assertTrue(Class.forName(model.getClass().getName()).equals(
model.getClass()));
}
@Test
public void testForInheritance() throws ClassNotFoundException {
Object model = new ScriptBriefResultModel();
assertEquals(ScriptBriefResultModel.class.getName(), model.getClass()
.getName());
}
}

View File

@ -1,30 +1,30 @@
package ModelTest;
import javax.xml.bind.JAXBException;
import static org.junit.Assert.*;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.RunningAgentModel;
import org.junit.Test;
public class MarshallerTest {
@Test
public void testMarshal() throws ClassNotFoundException, JAXBException {
RunningAgentModel runningAgentModel = new RunningAgentModel();
String contentString = MarshalHelper.marshal(RunningAgentModel.class,
runningAgentModel);
assertNotNull(contentString);
System.out.println(contentString);
}
@Test
public void testUnmarshal() throws JAXBException {
RunningAgentModel input = new RunningAgentModel();
String content = MarshalHelper.marshal(RunningAgentModel.class, input);
RunningAgentModel output = (RunningAgentModel) MarshalHelper.unmarshal(
RunningAgentModel.class, content);
System.out.println(input.getLoadInUse());
assertTrue(input.getLoadInUse() == output.getLoadInUse());
}
}
package ModelTest;
import javax.xml.bind.JAXBException;
import static org.junit.Assert.*;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.RunningAgentModel;
import org.junit.Test;
public class MarshallerTest {
@Test
public void testMarshal() throws ClassNotFoundException, JAXBException {
RunningAgentModel runningAgentModel = new RunningAgentModel();
String contentString = MarshalHelper.marshal(RunningAgentModel.class,
runningAgentModel);
assertNotNull(contentString);
System.out.println(contentString);
}
@Test
public void testUnmarshal() throws JAXBException {
RunningAgentModel input = new RunningAgentModel();
String content = MarshalHelper.marshal(RunningAgentModel.class, input);
RunningAgentModel output = (RunningAgentModel) MarshalHelper.unmarshal(
RunningAgentModel.class, content);
System.out.println(input.getLoadInUse());
assertTrue(input.getLoadInUse() == output.getLoadInUse());
}
}

View File

@ -1,42 +1,42 @@
package ModelTest;
import java.util.Date;
import javax.xml.bind.JAXBException;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptPageBriefModel;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test_StatisticsResultModel {
@Test
public void testScriptBrief() throws JAXBException {
ScriptBriefResultModel scriptBriefResultModel = new ScriptBriefResultModel();
scriptBriefResultModel.setSamplingTime(new Date());
System.out.println(MarshalHelper.marshal(ScriptBriefResultModel.class,
scriptBriefResultModel));
assertNotNull(scriptBriefResultModel.getSamplingTime());
}
@Test
public void testBehaviorsBrief() throws JAXBException {
ScriptBehaviorsBriefModel scriptBehaviorsBriefModel = new ScriptBehaviorsBriefModel();
scriptBehaviorsBriefModel.setSamplingTime(new Date());
System.out.println(MarshalHelper.marshal(
ScriptBehaviorsBriefModel.class, scriptBehaviorsBriefModel));
assertNotNull(scriptBehaviorsBriefModel.getSamplingTime());
}
@Test
public void testPageBrief() throws JAXBException {
ScriptPageBriefModel pageBriefModel = new ScriptPageBriefModel();
pageBriefModel.setSamplingTime(new Date());
System.out.println(MarshalHelper.marshal(ScriptPageBriefModel.class,
pageBriefModel));
assertNotNull(pageBriefModel.getSamplingTime());
}
}
package ModelTest;
import java.util.Date;
import javax.xml.bind.JAXBException;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptPageBriefModel;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test_StatisticsResultModel {
@Test
public void testScriptBrief() throws JAXBException {
ScriptBriefResultModel scriptBriefResultModel = new ScriptBriefResultModel();
scriptBriefResultModel.setSamplingTime(new Date());
System.out.println(MarshalHelper.marshal(ScriptBriefResultModel.class,
scriptBriefResultModel));
assertNotNull(scriptBriefResultModel.getSamplingTime());
}
@Test
public void testBehaviorsBrief() throws JAXBException {
ScriptBehaviorsBriefModel scriptBehaviorsBriefModel = new ScriptBehaviorsBriefModel();
scriptBehaviorsBriefModel.setSamplingTime(new Date());
System.out.println(MarshalHelper.marshal(
ScriptBehaviorsBriefModel.class, scriptBehaviorsBriefModel));
assertNotNull(scriptBehaviorsBriefModel.getSamplingTime());
}
@Test
public void testPageBrief() throws JAXBException {
ScriptPageBriefModel pageBriefModel = new ScriptPageBriefModel();
pageBriefModel.setSamplingTime(new Date());
System.out.println(MarshalHelper.marshal(ScriptPageBriefModel.class,
pageBriefModel));
assertNotNull(pageBriefModel.getSamplingTime());
}
}

View File

@ -1,68 +1,68 @@
package MonitorModelTest;
import static org.junit.Assert.*;
import org.bench4q.master.infrastructure.communication.MonitorMessenger;
import org.bench4q.share.models.master.MonitorModel;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class MonitorModelTest {
private MonitorModel monitor;
private MonitorMessenger monitorMessenger;
public MonitorMessenger getMonitorMessenger() {
return monitorMessenger;
}
@Autowired
public void setMonitorMessenger(MonitorMessenger monitorMessenger) {
this.monitorMessenger = monitorMessenger;
}
@Before
public void setUp() {
this.monitor = new MonitorModel();
monitor.setHostName("127.0.0.1");
monitor.setPort(5556);
}
@Test
public void testMemeoryModel() {
assertTrue(this.monitor.getHostName().equals("127.0.0.1"));
assertTrue(this.monitor.getPort() == 5556);
Assert.assertNotNull(this.getMonitorMessenger().memory(
monitor.getHostName(), monitor.getPort()));
}
@Test
public void testProcessorModel() {
Assert.assertNotNull(this.getMonitorMessenger().processor(
monitor.getHostName(), monitor.getPort()));
}
@Test
public void testProcessModel() {
Assert.assertNotNull(this.getMonitorMessenger().process(
monitor.getHostName(), monitor.getPort()));
}
@Test
public void testPhysicalDiskModel() {
Assert.assertNotNull(this.getMonitorMessenger().physicalDisk(
monitor.getHostName(), monitor.getPort()));
}
@Test
public void testMonitorMain() {
Assert.assertNotNull(this.getMonitorMessenger().monitorModel(
monitor.getHostName(), monitor.getPort()));
}
}
package MonitorModelTest;
import static org.junit.Assert.*;
import org.bench4q.master.infrastructure.communication.MonitorMessenger;
import org.bench4q.share.models.master.MonitorModel;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class MonitorModelTest {
private MonitorModel monitor;
private MonitorMessenger monitorMessenger;
public MonitorMessenger getMonitorMessenger() {
return monitorMessenger;
}
@Autowired
public void setMonitorMessenger(MonitorMessenger monitorMessenger) {
this.monitorMessenger = monitorMessenger;
}
@Before
public void setUp() {
this.monitor = new MonitorModel();
monitor.setHostName("127.0.0.1");
monitor.setPort(5556);
}
@Test
public void testMemeoryModel() {
assertTrue(this.monitor.getHostName().equals("127.0.0.1"));
assertTrue(this.monitor.getPort() == 5556);
Assert.assertNotNull(this.getMonitorMessenger().memory(
monitor.getHostName(), monitor.getPort()));
}
@Test
public void testProcessorModel() {
Assert.assertNotNull(this.getMonitorMessenger().processor(
monitor.getHostName(), monitor.getPort()));
}
@Test
public void testProcessModel() {
Assert.assertNotNull(this.getMonitorMessenger().process(
monitor.getHostName(), monitor.getPort()));
}
@Test
public void testPhysicalDiskModel() {
Assert.assertNotNull(this.getMonitorMessenger().physicalDisk(
monitor.getHostName(), monitor.getPort()));
}
@Test
public void testMonitorMain() {
Assert.assertNotNull(this.getMonitorMessenger().monitorModel(
monitor.getHostName(), monitor.getPort()));
}
}

View File

@ -1,7 +1,7 @@
package org.bench4q.master.test;
public class FileSeperatorTest {
public static void main(String[] args) {
System.out.println("scripts" + System.getProperty("file.separator"));
}
}
package org.bench4q.master.test;
public class FileSeperatorTest {
public static void main(String[] args) {
System.out.println("scripts" + System.getProperty("file.separator"));
}
}

View File

@ -1,51 +1,51 @@
package org.bench4q.master.test;
import java.io.IOException;
import org.bench4q.share.communication.HttpRequester;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.TestPlanModel;
import org.junit.Test;
public class HttpRequestTest {
private HttpRequester httpRequester;
public HttpRequester getHttpRequester() {
return httpRequester;
}
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
public HttpRequestTest() {
this.setHttpRequester(new HttpRequester());
}
@Test
public void testForError() {
try {
HttpResponse httpResponse = this
.getHttpRequester()
.sendPostXml(
"http://127.0.0.1:7979/testPlan/runTestPlanWithTestPlanModel",
MarshalHelper.marshal(TestPlanModel.class,
new TestPlanModel()), null);
System.out.println(httpResponse.getCode());
} catch (Exception e) {
e.printStackTrace();
}
}
public void testForRight() {
try {
HttpResponse httpResponse = this.getHttpRequester().sendGet(
"127.0.0.1:7979/", null, null);
System.out.println(httpResponse.getCode());
} catch (IOException e) {
e.printStackTrace();
}
}
}
package org.bench4q.master.test;
import java.io.IOException;
import org.bench4q.share.communication.HttpRequester;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.TestPlanModel;
import org.junit.Test;
public class HttpRequestTest {
private HttpRequester httpRequester;
public HttpRequester getHttpRequester() {
return httpRequester;
}
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
public HttpRequestTest() {
this.setHttpRequester(new HttpRequester());
}
@Test
public void testForError() {
try {
HttpResponse httpResponse = this
.getHttpRequester()
.sendPostXml(
"http://127.0.0.1:7979/testPlan/runTestPlanWithTestPlanModel",
MarshalHelper.marshal(TestPlanModel.class,
new TestPlanModel()), null);
System.out.println(httpResponse.getCode());
} catch (Exception e) {
e.printStackTrace();
}
}
public void testForRight() {
try {
HttpResponse httpResponse = this.getHttpRequester().sendGet(
"127.0.0.1:7979/", null, null);
System.out.println(httpResponse.getCode());
} catch (IOException e) {
e.printStackTrace();
}
}
}

View File

@ -1,29 +1,29 @@
package org.bench4q.master.test;
public class PolymorphismTest {
public void shout() {
shoutTwice();
}
public void shoutTwice() {
System.out.println("aaaaaa");
System.out.println("aaaaaa");
}
public static void main(String[] args) {
PolymorphismTest poly = new ChildTest();
System.out.println("poly shout is ");
poly.shout();
ChildTest childTest = new ChildTest();
System.out.println("child shout is ");
childTest.shout();
}
}
class ChildTest extends PolymorphismTest {
public void shoutTwice() {
System.out.println("bbbbbbb");
System.out.println("bbbbbbb");
}
package org.bench4q.master.test;
public class PolymorphismTest {
public void shout() {
shoutTwice();
}
public void shoutTwice() {
System.out.println("aaaaaa");
System.out.println("aaaaaa");
}
public static void main(String[] args) {
PolymorphismTest poly = new ChildTest();
System.out.println("poly shout is ");
poly.shout();
ChildTest childTest = new ChildTest();
System.out.println("child shout is ");
childTest.shout();
}
}
class ChildTest extends PolymorphismTest {
public void shoutTwice() {
System.out.println("bbbbbbb");
System.out.println("bbbbbbb");
}
}

View File

@ -1,24 +1,24 @@
package org.bench4q.master.test;
import static org.junit.Assert.*;
import org.junit.Test;
public class byteTest {
@Test
public void testByteForNewLine() {
Byte byte1 = Byte.parseByte("10");
assertTrue(byte1.byteValue() == 10);
char ch = (char) byte1.byteValue();
assertEquals('\n', ch);
System.out.println(ch);
}
@Test
public void testByteForReturn() {
Byte byte2 = Byte.parseByte("13");
char ch = (char) byte2.byteValue();
assertEquals('\r', ch);
System.out.println(ch);
}
}
package org.bench4q.master.test;
import static org.junit.Assert.*;
import org.junit.Test;
public class byteTest {
@Test
public void testByteForNewLine() {
Byte byte1 = Byte.parseByte("10");
assertTrue(byte1.byteValue() == 10);
char ch = (char) byte1.byteValue();
assertEquals('\n', ch);
System.out.println(ch);
}
@Test
public void testByteForReturn() {
Byte byte2 = Byte.parseByte("13");
char ch = (char) byte2.byteValue();
assertEquals('\r', ch);
System.out.println(ch);
}
}

View File

@ -1,40 +1,40 @@
package org.bench4q.master.test.communication;
import org.bench4q.master.domain.entity.Monitor;
import org.bench4q.master.infrastructure.communication.MonitorMessenger;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_MonitorMessenger {
private Monitor monitor = new Monitor();
private MonitorMessenger monitorMessenger;
@Before
public void setUp() {
this.monitor.setHostName("127.0.0.1");
this.monitor.setPort(5556);
}
public MonitorMessenger getMonitorMessenger() {
return monitorMessenger;
}
@Autowired
public void setMonitorMessenger(MonitorMessenger monitorMessenger) {
this.monitorMessenger = monitorMessenger;
}
@Test
public void test_getMonitorModel() {
Assert.assertNotNull(this.getMonitorMessenger().monitorModel(
monitor.getHostName(), monitor.getPort()));
}
}
package org.bench4q.master.test.communication;
import org.bench4q.master.domain.entity.Monitor;
import org.bench4q.master.infrastructure.communication.MonitorMessenger;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_MonitorMessenger {
private Monitor monitor = new Monitor();
private MonitorMessenger monitorMessenger;
@Before
public void setUp() {
this.monitor.setHostName("127.0.0.1");
this.monitor.setPort(5556);
}
public MonitorMessenger getMonitorMessenger() {
return monitorMessenger;
}
@Autowired
public void setMonitorMessenger(MonitorMessenger monitorMessenger) {
this.monitorMessenger = monitorMessenger;
}
@Test
public void test_getMonitorModel() {
Assert.assertNotNull(this.getMonitorMessenger().monitorModel(
monitor.getHostName(), monitor.getPort()));
}
}

View File

@ -1,75 +1,75 @@
package org.bench4q.master.test.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.AgentModel;
import org.bench4q.share.models.master.AgentResponseModel;
import org.junit.Test;
public class AgentPoolControllerTest extends TestBase {
private final String URLSTRING = BASE_URL + "/agentManage";
private final static String HOSTNAME1 = "127.0.0.1";
private final static String HOSTNAME2 = "133.133.12.9";
@Test
public void testAdd() throws JAXBException, IOException {
this.setAccessTocken(this.login());
this.addAgentToPool(HOSTNAME2);
// test.removeAgentToPool();
this.loadAgentsFromPool();
}
public void addAgentToPool(String hostName) throws JAXBException,
IOException {
String urlString = this.URLSTRING + "/addAgentToPool";
AgentResponseModel agentResponseModel = new AgentResponseModel();
AgentModel agent = new AgentModel();
agent.setHostName(hostName);
agent.setMaxLoad(500);
agent.setRemainLoad(500);
agent.setPort(6565);
System.out.println(urlString);
System.out.println(MarshalHelper.marshal(AgentModel.class, agent));
HttpResponse httpResponse = this.httpRequester.sendPostXml(urlString,
MarshalHelper.marshal(AgentModel.class, agent),
makeAccessTockenMap(this.getAccessTocken()));
agentResponseModel = (AgentResponseModel) MarshalHelper.unmarshal(
AgentResponseModel.class, httpResponse.getContent());
System.out.println(httpResponse.getContent());
System.out.println(agentResponseModel.isSuccess());
}
public void removeAgentToPool() throws IOException, JAXBException {
Map<String, String> propertiesMap = new HashMap<String, String>();
propertiesMap.put(AUTH_HEADER_PROPERTY, this.ACCES_TOCKEN_STARTER
+ this.accessTocken);
String urlString = this.URLSTRING + "/removeAgentFromPool";
Map<String, String> map = new HashMap<String, String>();
map.put("hostName", HOSTNAME1);
HttpResponse httpResponse = this.httpRequester.sendGet(urlString, map,
propertiesMap);
System.out.println(httpResponse.getContent());
}
public void loadAgentsFromPool() throws IOException {
Map<String, String> propertiesMap = new HashMap<String, String>();
propertiesMap.put(AUTH_HEADER_PROPERTY, this.ACCES_TOCKEN_STARTER
+ this.accessTocken);
String urlString = this.URLSTRING + "/queryAgentList";
HttpResponse httpResponse = this.httpRequester.sendPost(urlString,
null, propertiesMap);
System.out.println(httpResponse.getContent());
}
}
package org.bench4q.master.test.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.AgentModel;
import org.bench4q.share.models.master.AgentResponseModel;
import org.junit.Test;
public class AgentPoolControllerTest extends TestBase {
private final String URLSTRING = BASE_URL + "/agentManage";
private final static String HOSTNAME1 = "127.0.0.1";
private final static String HOSTNAME2 = "133.133.12.9";
@Test
public void testAdd() throws JAXBException, IOException {
this.setAccessTocken(this.login());
this.addAgentToPool(HOSTNAME2);
// test.removeAgentToPool();
this.loadAgentsFromPool();
}
public void addAgentToPool(String hostName) throws JAXBException,
IOException {
String urlString = this.URLSTRING + "/addAgentToPool";
AgentResponseModel agentResponseModel = new AgentResponseModel();
AgentModel agent = new AgentModel();
agent.setHostName(hostName);
agent.setMaxLoad(500);
agent.setRemainLoad(500);
agent.setPort(6565);
System.out.println(urlString);
System.out.println(MarshalHelper.marshal(AgentModel.class, agent));
HttpResponse httpResponse = this.httpRequester.sendPostXml(urlString,
MarshalHelper.marshal(AgentModel.class, agent),
makeAccessTockenMap(this.getAccessTocken()));
agentResponseModel = (AgentResponseModel) MarshalHelper.unmarshal(
AgentResponseModel.class, httpResponse.getContent());
System.out.println(httpResponse.getContent());
System.out.println(agentResponseModel.isSuccess());
}
public void removeAgentToPool() throws IOException, JAXBException {
Map<String, String> propertiesMap = new HashMap<String, String>();
propertiesMap.put(AUTH_HEADER_PROPERTY, this.ACCES_TOCKEN_STARTER
+ this.accessTocken);
String urlString = this.URLSTRING + "/removeAgentFromPool";
Map<String, String> map = new HashMap<String, String>();
map.put("hostName", HOSTNAME1);
HttpResponse httpResponse = this.httpRequester.sendGet(urlString, map,
propertiesMap);
System.out.println(httpResponse.getContent());
}
public void loadAgentsFromPool() throws IOException {
Map<String, String> propertiesMap = new HashMap<String, String>();
propertiesMap.put(AUTH_HEADER_PROPERTY, this.ACCES_TOCKEN_STARTER
+ this.accessTocken);
String urlString = this.URLSTRING + "/queryAgentList";
HttpResponse httpResponse = this.httpRequester.sendPost(urlString,
null, propertiesMap);
System.out.println(httpResponse.getContent());
}
}

View File

@ -1,43 +1,43 @@
package org.bench4q.master.test.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
public class RecordPortControllerTest extends TestBase {
private final String URLSTRING = BASE_URL + "/RecordPort";
private final String PORT = "1100";
private final String PARAM1 = "port";
public void AddPortToPool() throws IOException, JAXBException {
String accesTocken = this.login();
Map<String, String> params = new HashMap<String, String>();
params.put(PARAM1, PORT);
String urlString = URLSTRING + "/addPortToPortPool";
HttpResponse httpResponse = this.httpRequester.sendPost(urlString,
params, this.makeAccessTockenMap(accesTocken));
System.out.println(httpResponse.getContent());
}
public void RemovePortFromPool() throws IOException, JAXBException {
String accesTocken = this.login();
Map<String, String> params = new HashMap<String, String>();
params.put("portId", 3 + "");
String urlString = URLSTRING + "/removePortFromPool";
HttpResponse httpResponse = this.httpRequester.sendPost(urlString,
params, this.makeAccessTockenMap(accesTocken));
System.out.println(httpResponse.getContent());
}
public static void main(String[] args) throws Throwable {
RecordPortControllerTest test = new RecordPortControllerTest();
test.AddPortToPool();
test.RemovePortFromPool();
}
}
package org.bench4q.master.test.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
public class RecordPortControllerTest extends TestBase {
private final String URLSTRING = BASE_URL + "/RecordPort";
private final String PORT = "1100";
private final String PARAM1 = "port";
public void AddPortToPool() throws IOException, JAXBException {
String accesTocken = this.login();
Map<String, String> params = new HashMap<String, String>();
params.put(PARAM1, PORT);
String urlString = URLSTRING + "/addPortToPortPool";
HttpResponse httpResponse = this.httpRequester.sendPost(urlString,
params, this.makeAccessTockenMap(accesTocken));
System.out.println(httpResponse.getContent());
}
public void RemovePortFromPool() throws IOException, JAXBException {
String accesTocken = this.login();
Map<String, String> params = new HashMap<String, String>();
params.put("portId", 3 + "");
String urlString = URLSTRING + "/removePortFromPool";
HttpResponse httpResponse = this.httpRequester.sendPost(urlString,
params, this.makeAccessTockenMap(accesTocken));
System.out.println(httpResponse.getContent());
}
public static void main(String[] args) throws Throwable {
RecordPortControllerTest test = new RecordPortControllerTest();
test.AddPortToPool();
test.RemovePortFromPool();
}
}

View File

@ -1,90 +1,90 @@
package org.bench4q.master.test.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import static org.junit.Assert.*;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.agent.RunScenarioModel;
import org.bench4q.share.models.master.OperateScriptServerResponseModel;
import org.bench4q.share.models.master.ScriptModel;
import org.junit.Test;
public class RecordScriptControllerTest extends TestBase {
private static final int RECORD_TIME = 60000;
private final String SCRIPT_URL = TestBase.BASE_URL + "/RecordScript";
public OperateScriptServerResponseModel startRecord() throws IOException,
JAXBException {
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
+ "/startScriptRecordServer", null,
this.makeAccessTockenMap(this.getAccessTocken()));
System.out.println(httpResponse.getContent());
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
.unmarshal(OperateScriptServerResponseModel.class,
httpResponse.getContent());
assertTrue(ret.isSuccess());
return ret;
}
public void stopRecord(OperateScriptServerResponseModel model)
throws IOException, JAXBException {
Map<String, String> paramsMap = buildParams("port",
String.valueOf(model.getPort()));
paramsMap.put("fileNameUUID", model.getFileName());
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
+ "/stopScriptRecordServer", paramsMap,
this.makeAccessTockenMap(this.accessTocken));
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
.unmarshal(OperateScriptServerResponseModel.class,
httpResponse.getContent());
assertTrue(ret.isSuccess());
}
private Map<String, String> buildParams(String key, String value) {
Map<String, String> params = new HashMap<String, String>();
params.put(key, value);
return params;
}
public ScriptModel saveScriptToDB(OperateScriptServerResponseModel model,
String scriptName) throws IOException, JAXBException {
Map<String, String> params = new HashMap<String, String>();
params.put("scriptName", scriptName);
params.put("port", String.valueOf(model.getPort()));
params.put("fileNameUUID", model.getFileName());
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
+ "/saveScriptToDB", params,
this.makeAccessTockenMap(this.getAccessTocken()));
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
.unmarshal(OperateScriptServerResponseModel.class,
httpResponse.getContent());
assertTrue(ret.isSuccess());
assertNotNull(ret.getScriptModels());
assertNotNull(ret.getScriptModels().get(0));
return ret.getScriptModels().get(0);
}
@Test
public void testRecordScript() throws IOException, JAXBException,
InterruptedException {
RecordScriptControllerTest test = new RecordScriptControllerTest();
test.accessTocken = test.login();
Thread.sleep(1000);
OperateScriptServerResponseModel model = test.startRecord();
Thread.sleep(RECORD_TIME);
System.out.println("Thread has waken up");
test.stopRecord(model);
ScriptModel scriptModel = test.saveScriptToDB(model, "chen2");
assertNotNull(scriptModel.getScriptContent());
RunScenarioModel runScenarioModel = (RunScenarioModel) MarshalHelper
.unmarshal(RunScenarioModel.class,
scriptModel.getScriptContent());
assertNotNull(runScenarioModel);
}
}
package org.bench4q.master.test.controller;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import static org.junit.Assert.*;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.agent.RunScenarioModel;
import org.bench4q.share.models.master.OperateScriptServerResponseModel;
import org.bench4q.share.models.master.ScriptModel;
import org.junit.Test;
public class RecordScriptControllerTest extends TestBase {
private static final int RECORD_TIME = 60000;
private final String SCRIPT_URL = TestBase.BASE_URL + "/RecordScript";
public OperateScriptServerResponseModel startRecord() throws IOException,
JAXBException {
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
+ "/startScriptRecordServer", null,
this.makeAccessTockenMap(this.getAccessTocken()));
System.out.println(httpResponse.getContent());
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
.unmarshal(OperateScriptServerResponseModel.class,
httpResponse.getContent());
assertTrue(ret.isSuccess());
return ret;
}
public void stopRecord(OperateScriptServerResponseModel model)
throws IOException, JAXBException {
Map<String, String> paramsMap = buildParams("port",
String.valueOf(model.getPort()));
paramsMap.put("fileNameUUID", model.getFileName());
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
+ "/stopScriptRecordServer", paramsMap,
this.makeAccessTockenMap(this.accessTocken));
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
.unmarshal(OperateScriptServerResponseModel.class,
httpResponse.getContent());
assertTrue(ret.isSuccess());
}
private Map<String, String> buildParams(String key, String value) {
Map<String, String> params = new HashMap<String, String>();
params.put(key, value);
return params;
}
public ScriptModel saveScriptToDB(OperateScriptServerResponseModel model,
String scriptName) throws IOException, JAXBException {
Map<String, String> params = new HashMap<String, String>();
params.put("scriptName", scriptName);
params.put("port", String.valueOf(model.getPort()));
params.put("fileNameUUID", model.getFileName());
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
+ "/saveScriptToDB", params,
this.makeAccessTockenMap(this.getAccessTocken()));
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
.unmarshal(OperateScriptServerResponseModel.class,
httpResponse.getContent());
assertTrue(ret.isSuccess());
assertNotNull(ret.getScriptModels());
assertNotNull(ret.getScriptModels().get(0));
return ret.getScriptModels().get(0);
}
@Test
public void testRecordScript() throws IOException, JAXBException,
InterruptedException {
RecordScriptControllerTest test = new RecordScriptControllerTest();
test.accessTocken = test.login();
Thread.sleep(1000);
OperateScriptServerResponseModel model = test.startRecord();
Thread.sleep(RECORD_TIME);
System.out.println("Thread has waken up");
test.stopRecord(model);
ScriptModel scriptModel = test.saveScriptToDB(model, "chen2");
assertNotNull(scriptModel.getScriptContent());
RunScenarioModel runScenarioModel = (RunScenarioModel) MarshalHelper
.unmarshal(RunScenarioModel.class,
scriptModel.getScriptContent());
assertNotNull(runScenarioModel);
}
}

View File

@ -1,42 +1,42 @@
package org.bench4q.master.test.controller;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.OperateScriptServerResponseModel;
import org.junit.Test;
public class ScriptControllerTest extends TestBase {
private String controllerUrl = BASE_URL + "/RecordScript";
@Test
public void loadScriptsTest() throws IOException, JAXBException {
String url = this.controllerUrl + "/loadScriptList";
HttpResponse httpResponse = this.httpRequester.sendGet(url, null,
this.makeAccessTockenMap(this.login()));
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
.unmarshal(OperateScriptServerResponseModel.class,
httpResponse.getContent());
assertTrue(ret.getScriptModels().size() > 0);
}
@Test
public void deleteScript(int scriptId) throws IOException {
Map<String, String> params = new HashMap<String, String>();
params.put("scriptId", scriptId + "");
Map<String, String> properties = new HashMap<String, String>();
properties.put(this.AUTH_HEADER_PROPERTY, this.ACCES_TOCKEN_STARTER
+ this.accessTocken);
HttpResponse httpResponse = this.httpRequester.sendPost(
this.controllerUrl + "/deleteScript", params, properties);
System.out.println(httpResponse.getContent());
}
}
package org.bench4q.master.test.controller;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.OperateScriptServerResponseModel;
import org.junit.Test;
public class ScriptControllerTest extends TestBase {
private String controllerUrl = BASE_URL + "/RecordScript";
@Test
public void loadScriptsTest() throws IOException, JAXBException {
String url = this.controllerUrl + "/loadScriptList";
HttpResponse httpResponse = this.httpRequester.sendGet(url, null,
this.makeAccessTockenMap(this.login()));
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
.unmarshal(OperateScriptServerResponseModel.class,
httpResponse.getContent());
assertTrue(ret.getScriptModels().size() > 0);
}
@Test
public void deleteScript(int scriptId) throws IOException {
Map<String, String> params = new HashMap<String, String>();
params.put("scriptId", scriptId + "");
Map<String, String> properties = new HashMap<String, String>();
properties.put(this.AUTH_HEADER_PROPERTY, this.ACCES_TOCKEN_STARTER
+ this.accessTocken);
HttpResponse httpResponse = this.httpRequester.sendPost(
this.controllerUrl + "/deleteScript", params, properties);
System.out.println(httpResponse.getContent());
}
}

View File

@ -1,59 +1,59 @@
package org.bench4q.master.test.controller;
import java.util.HashMap;
import java.util.Map;
import org.bench4q.share.communication.HttpRequester;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.AuthorizeResponseModel;
public class TestBase {
protected HttpRequester httpRequester = new HttpRequester();
private final String USERNAME = "admin";
private final String PASSWORD = "admin";
public static final String BASE_URL = "http://localhost:7979";
// public static final String BASE_URL =
// "http://bench4q_master.jd-app.com:80";
protected final String AUTH_HEADER_PROPERTY = "Authorization";
protected final String ACCES_TOCKEN_STARTER = "Bearer ";
protected String accessTocken;
public String getAccessTocken() {
return accessTocken;
}
public void setAccessTocken(String accessTocken) {
this.accessTocken = accessTocken;
}
public TestBase() {
this.setAccessTocken(this.login());
}
public String login() {
String urlString = BASE_URL + "/user/adminAuthorize";
Map<String, String> map = new HashMap<String, String>();
map.put("userName", USERNAME);
map.put("password", PASSWORD);
HttpResponse httpResponse;
try {
httpResponse = this.httpRequester.sendGet(urlString, map, null);
System.out.println("http content:"+httpResponse.getContent());
return ((AuthorizeResponseModel) MarshalHelper.unmarshal(
AuthorizeResponseModel.class, httpResponse.getContent()))
.getAccessToken();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Map<String, String> makeAccessTockenMap(String accessToken) {
Map<String, String> properties = new HashMap<String, String>();
properties
.put(AUTH_HEADER_PROPERTY, ACCES_TOCKEN_STARTER + accessToken);
return properties;
}
}
package org.bench4q.master.test.controller;
import java.util.HashMap;
import java.util.Map;
import org.bench4q.share.communication.HttpRequester;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.AuthorizeResponseModel;
public class TestBase {
protected HttpRequester httpRequester = new HttpRequester();
private final String USERNAME = "admin";
private final String PASSWORD = "admin";
public static final String BASE_URL = "http://localhost:7979";
// public static final String BASE_URL =
// "http://bench4q_master.jd-app.com:80";
protected final String AUTH_HEADER_PROPERTY = "Authorization";
protected final String ACCES_TOCKEN_STARTER = "Bearer ";
protected String accessTocken;
public String getAccessTocken() {
return accessTocken;
}
public void setAccessTocken(String accessTocken) {
this.accessTocken = accessTocken;
}
public TestBase() {
this.setAccessTocken(this.login());
}
public String login() {
String urlString = BASE_URL + "/user/adminAuthorize";
Map<String, String> map = new HashMap<String, String>();
map.put("userName", USERNAME);
map.put("password", PASSWORD);
HttpResponse httpResponse;
try {
httpResponse = this.httpRequester.sendGet(urlString, map, null);
System.out.println("http content:"+httpResponse.getContent());
return ((AuthorizeResponseModel) MarshalHelper.unmarshal(
AuthorizeResponseModel.class, httpResponse.getContent()))
.getAccessToken();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public Map<String, String> makeAccessTockenMap(String accessToken) {
Map<String, String> properties = new HashMap<String, String>();
properties
.put(AUTH_HEADER_PROPERTY, ACCES_TOCKEN_STARTER + accessToken);
return properties;
}
}

View File

@ -1,39 +1,39 @@
package org.bench4q.master.test.controller;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.master.test.TestBase_MakeUpTestPlan;
import org.bench4q.share.communication.HttpRequester;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.MonitorMemoryResponseModel;
import org.junit.Test;
public class Test_MonitorController extends TestBase_MakeUpTestPlan {
@Test
public void testMemoryInfo() throws IOException, JAXBException {
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanRunId", "90293f23-581a-40a2-93e3-f47035c06242");
params.put("hostName", "127.0.0.1");
params.put("port", "5556");
params.put("duationBegin", "0");
HttpResponse httpResponse = this.httpRequester.sendGet(BASE_URL
+ "/monitorController/memorySUTInfo", params,
makeAccessTockenMap(this.getAccessTocken()));
System.out.println(httpResponse.getContent());
if (HttpRequester.isInvalidResponse(httpResponse)) {
fail("not valid response!");
}
MonitorMemoryResponseModel memoryResponseModel = (MonitorMemoryResponseModel) MarshalHelper
.unmarshal(MonitorMemoryResponseModel.class,
httpResponse.getContent());
assertEquals(3, memoryResponseModel.getMemoryModels().size());
}
}
package org.bench4q.master.test.controller;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.master.test.TestBase_MakeUpTestPlan;
import org.bench4q.share.communication.HttpRequester;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.MonitorMemoryResponseModel;
import org.junit.Test;
public class Test_MonitorController extends TestBase_MakeUpTestPlan {
@Test
public void testMemoryInfo() throws IOException, JAXBException {
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanRunId", "90293f23-581a-40a2-93e3-f47035c06242");
params.put("hostName", "127.0.0.1");
params.put("port", "5556");
params.put("duationBegin", "0");
HttpResponse httpResponse = this.httpRequester.sendGet(BASE_URL
+ "/monitorController/memorySUTInfo", params,
makeAccessTockenMap(this.getAccessTocken()));
System.out.println(httpResponse.getContent());
if (HttpRequester.isInvalidResponse(httpResponse)) {
fail("not valid response!");
}
MonitorMemoryResponseModel memoryResponseModel = (MonitorMemoryResponseModel) MarshalHelper
.unmarshal(MonitorMemoryResponseModel.class,
httpResponse.getContent());
assertEquals(3, memoryResponseModel.getMemoryModels().size());
}
}

View File

@ -1,10 +1,10 @@
package org.bench4q.master.test.datastatistics;
import org.junit.Test;
public class BehaviorsBriefStatisticsTest {
@Test
public void testAddNull() {
}
}
package org.bench4q.master.test.datastatistics;
import org.junit.Test;
public class BehaviorsBriefStatisticsTest {
@Test
public void testAddNull() {
}
}

View File

@ -1,145 +1,145 @@
package org.bench4q.master.test.datastatistics;
import static org.junit.Assert.*;
import org.bench4q.master.domain.valueobject.datastatistics.ScriptBriefStatistics;
import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.junit.Test;
public class ScriptBriefStatisticsTest {
private ScriptBriefStatistics briefStatistics;
private static int TIME_UNIT_MS = 1000;
private static int FAIL_COUNT = 1;
public ScriptBriefStatistics getBriefStatistics() {
return briefStatistics;
}
public void setBriefStatistics(ScriptBriefStatistics briefStatistics) {
this.briefStatistics = briefStatistics;
}
public ScriptBriefStatisticsTest() {
this.setBriefStatistics(new ScriptBriefStatistics());
}
@Test
public void addNullTest() {
this.getBriefStatistics().add(null);
}
@Test
public void addZeroTest() {
briefStatistics.add(new AgentBriefStatusModel());
ScriptBriefResultModel actualResult = briefStatistics.getStatistics();
ScriptBriefResultModel expectedResult = makeExpectedModelForZeroAgent();
assertTrue(actualResult.equals(expectedResult));
assertEquals(0, actualResult.getvUserCount());
}
private ScriptBriefResultModel makeExpectedModelForZeroAgent() {
ScriptBriefResultModel result = new ScriptBriefResultModel();
result.setAverageElapsedTime(0);
result.setAverageResponseTime(0);
result.setFailRateThisTime(0);
result.setFailThroughputThisTime(0);
result.setMaxResponseTime(0);
result.setMinResponseTime(0);
result.setResponseTimeDeviationThisTime(0);
result.setSuccessThroughputThisTime(0);
result.setTotalFailCountFromBegin(0);
result.setTotalSuccessCountFromBegin(0);
result.setvUserCount(0);
return result;
}
@Test
public void addOneTest() {
long timeFrame = 200;
this.getBriefStatistics().add(
buildOneInputModel(timeFrame, 200, 200, 200, 40000, 1, 10));
ScriptBriefResultModel actualModel = this.getBriefStatistics()
.getStatistics();
ScriptBriefResultModel expectedModel = this
.makeExepectedModelForOneAgent();
assertTrue(actualModel.equals(expectedModel));
}
@Test
public void addOneTestWithNegativeVUser() {
long timeFrame = 200;
this.getBriefStatistics().add(
buildOneInputModel(timeFrame, 200, 200, 200, 40000, 1, -2));
ScriptBriefResultModel actualModel = this.getBriefStatistics()
.getStatistics();
ScriptBriefResultModel expectedBriefResultModel = this
.makeExepectedModelForOneAgent();
expectedBriefResultModel.setvUserCount(-2);
assertTrue(actualModel.equals(expectedBriefResultModel));
}
public static AgentBriefStatusModel buildOneInputModel(long timeFrame,
long minRT, long maxRT, long totalRT, long totalSqureRT,
long successCount, long vUserCount) {
AgentBriefStatusModel model = new AgentBriefStatusModel();
model.setTimeFrame(timeFrame);
model.setSuccessCountFromBegin(successCount);
model.setFailCountFromBegin(FAIL_COUNT);
model.setSuccessThroughputThisTime(successCount * TIME_UNIT_MS
/ timeFrame);
model.setFailThroughputThisTime(FAIL_COUNT * TIME_UNIT_MS / timeFrame);
model.setMaxResponseTime(maxRT);
model.setMinResponseTime(minRT);
model.setSuccessCountThisTime(successCount);
model.setFailCountThisTime(FAIL_COUNT);
model.setTotalResponseTimeThisTime(totalRT);
model.setTotalSqureResponseTimeThisTime(totalSqureRT);
model.setvUserCount(vUserCount);
return model;
}
private ScriptBriefResultModel makeExepectedModelForOneAgent() {
ScriptBriefResultModel result = new ScriptBriefResultModel();
result.setAverageResponseTime(200);
result.setFailRateThisTime(50);
result.setFailThroughputThisTime(1 * TIME_UNIT_MS / 200);
result.setMaxResponseTime(200);
result.setMinResponseTime(200);
result.setResponseTimeDeviationThisTime(0);
result.setSuccessThroughputThisTime(1 * TIME_UNIT_MS / 200);
result.setTotalFailCountFromBegin(1);
result.setTotalSuccessCountFromBegin(1);
result.setvUserCount(10);
return result;
}
@Test
public void addTwoTest() {
long timeFrame1 = 200, timeFrame2 = 500;
this.briefStatistics.add(buildOneInputModel(timeFrame1, 200, 200, 200,
40000, 1, 10));
this.briefStatistics.add(buildOneInputModel(timeFrame2, 190, 210, 400,
80200, 2, 20));
ScriptBriefResultModel actualModel = this.briefStatistics
.getStatistics();
ScriptBriefResultModel expectedModel = makeExpectedModelForTwoAgent();
assertTrue(actualModel.equals(expectedModel));
}
private ScriptBriefResultModel makeExpectedModelForTwoAgent() {
ScriptBriefResultModel result = new ScriptBriefResultModel();
result.setAverageResponseTime(200);
result.setFailRateThisTime(40);
result.setFailThroughputThisTime(7);
result.setMaxResponseTime(210);
result.setMinResponseTime(190);
result.setResponseTimeDeviationThisTime(8);
result.setSuccessThroughputThisTime(9);
result.setTotalFailCountFromBegin(2);
result.setTotalSuccessCountFromBegin(3);
result.setvUserCount(30);
return result;
}
}
package org.bench4q.master.test.datastatistics;
import static org.junit.Assert.*;
import org.bench4q.master.domain.valueobject.datastatistics.ScriptBriefStatistics;
import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.junit.Test;
public class ScriptBriefStatisticsTest {
private ScriptBriefStatistics briefStatistics;
private static int TIME_UNIT_MS = 1000;
private static int FAIL_COUNT = 1;
public ScriptBriefStatistics getBriefStatistics() {
return briefStatistics;
}
public void setBriefStatistics(ScriptBriefStatistics briefStatistics) {
this.briefStatistics = briefStatistics;
}
public ScriptBriefStatisticsTest() {
this.setBriefStatistics(new ScriptBriefStatistics());
}
@Test
public void addNullTest() {
this.getBriefStatistics().add(null);
}
@Test
public void addZeroTest() {
briefStatistics.add(new AgentBriefStatusModel());
ScriptBriefResultModel actualResult = briefStatistics.getStatistics();
ScriptBriefResultModel expectedResult = makeExpectedModelForZeroAgent();
assertTrue(actualResult.equals(expectedResult));
assertEquals(0, actualResult.getvUserCount());
}
private ScriptBriefResultModel makeExpectedModelForZeroAgent() {
ScriptBriefResultModel result = new ScriptBriefResultModel();
result.setAverageElapsedTime(0);
result.setAverageResponseTime(0);
result.setFailRateThisTime(0);
result.setFailThroughputThisTime(0);
result.setMaxResponseTime(0);
result.setMinResponseTime(0);
result.setResponseTimeDeviationThisTime(0);
result.setSuccessThroughputThisTime(0);
result.setTotalFailCountFromBegin(0);
result.setTotalSuccessCountFromBegin(0);
result.setvUserCount(0);
return result;
}
@Test
public void addOneTest() {
long timeFrame = 200;
this.getBriefStatistics().add(
buildOneInputModel(timeFrame, 200, 200, 200, 40000, 1, 10));
ScriptBriefResultModel actualModel = this.getBriefStatistics()
.getStatistics();
ScriptBriefResultModel expectedModel = this
.makeExepectedModelForOneAgent();
assertTrue(actualModel.equals(expectedModel));
}
@Test
public void addOneTestWithNegativeVUser() {
long timeFrame = 200;
this.getBriefStatistics().add(
buildOneInputModel(timeFrame, 200, 200, 200, 40000, 1, -2));
ScriptBriefResultModel actualModel = this.getBriefStatistics()
.getStatistics();
ScriptBriefResultModel expectedBriefResultModel = this
.makeExepectedModelForOneAgent();
expectedBriefResultModel.setvUserCount(-2);
assertTrue(actualModel.equals(expectedBriefResultModel));
}
public static AgentBriefStatusModel buildOneInputModel(long timeFrame,
long minRT, long maxRT, long totalRT, long totalSqureRT,
long successCount, long vUserCount) {
AgentBriefStatusModel model = new AgentBriefStatusModel();
model.setTimeFrame(timeFrame);
model.setSuccessCountFromBegin(successCount);
model.setFailCountFromBegin(FAIL_COUNT);
model.setSuccessThroughputThisTime(successCount * TIME_UNIT_MS
/ timeFrame);
model.setFailThroughputThisTime(FAIL_COUNT * TIME_UNIT_MS / timeFrame);
model.setMaxResponseTime(maxRT);
model.setMinResponseTime(minRT);
model.setSuccessCountThisTime(successCount);
model.setFailCountThisTime(FAIL_COUNT);
model.setTotalResponseTimeThisTime(totalRT);
model.setTotalSqureResponseTimeThisTime(totalSqureRT);
model.setvUserCount(vUserCount);
return model;
}
private ScriptBriefResultModel makeExepectedModelForOneAgent() {
ScriptBriefResultModel result = new ScriptBriefResultModel();
result.setAverageResponseTime(200);
result.setFailRateThisTime(50);
result.setFailThroughputThisTime(1 * TIME_UNIT_MS / 200);
result.setMaxResponseTime(200);
result.setMinResponseTime(200);
result.setResponseTimeDeviationThisTime(0);
result.setSuccessThroughputThisTime(1 * TIME_UNIT_MS / 200);
result.setTotalFailCountFromBegin(1);
result.setTotalSuccessCountFromBegin(1);
result.setvUserCount(10);
return result;
}
@Test
public void addTwoTest() {
long timeFrame1 = 200, timeFrame2 = 500;
this.briefStatistics.add(buildOneInputModel(timeFrame1, 200, 200, 200,
40000, 1, 10));
this.briefStatistics.add(buildOneInputModel(timeFrame2, 190, 210, 400,
80200, 2, 20));
ScriptBriefResultModel actualModel = this.briefStatistics
.getStatistics();
ScriptBriefResultModel expectedModel = makeExpectedModelForTwoAgent();
assertTrue(actualModel.equals(expectedModel));
}
private ScriptBriefResultModel makeExpectedModelForTwoAgent() {
ScriptBriefResultModel result = new ScriptBriefResultModel();
result.setAverageResponseTime(200);
result.setFailRateThisTime(40);
result.setFailThroughputThisTime(7);
result.setMaxResponseTime(210);
result.setMinResponseTime(190);
result.setResponseTimeDeviationThisTime(8);
result.setSuccessThroughputThisTime(9);
result.setTotalFailCountFromBegin(2);
result.setTotalSuccessCountFromBegin(3);
result.setvUserCount(30);
return result;
}
}

View File

@ -1,109 +1,109 @@
package org.bench4q.master.test.datastatistics;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.bench4q.master.domain.valueobject.datastatistics.PageBriefStatistics;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.bench4q.share.models.master.statistics.ScriptPageBriefModel;
import org.junit.Test;
public class TestPageBrief {
private PageBriefStatistics statistics;
private PageBriefStatistics getStatistics() {
return statistics;
}
private void setStatistics(PageBriefStatistics statistics) {
this.statistics = statistics;
}
public TestPageBrief() {
this.setStatistics(new PageBriefStatistics());
}
@Test
public void testNull() {
this.getStatistics().add(null);
ScriptPageBriefModel scriptPageBriefModel = (ScriptPageBriefModel) this
.getStatistics().getStatistics();
assertTrue(scriptPageBriefModel != null);
assertEquals(0, scriptPageBriefModel.getCountFromBegin());
assertEquals(Long.MIN_VALUE,
scriptPageBriefModel.getMaxResponseTimeFromBegin());
assertEquals(Long.MAX_VALUE,
scriptPageBriefModel.getMinResponseTimeFromBegin());
assertEquals(0, scriptPageBriefModel.getAverageResponseTimeThisTime());
assertEquals(0, scriptPageBriefModel.getLatestResponseTime());
}
@Test
public void testOneWithZeroCountThisTimeForAverage() {
this.getStatistics().add(
buildAgentPageBriefModel(1, 1, 0, 200, 200, 200, 190, 0));
ScriptPageBriefModel pageBriefModel = (ScriptPageBriefModel) this
.getStatistics().getStatistics();
assertEquals(0, pageBriefModel.getAverageResponseTimeThisTime());
assertEquals(1, pageBriefModel.getCountFromBegin());
assertEquals(200, pageBriefModel.getLatestResponseTime());
assertEquals(200, pageBriefModel.getMaxResponseTimeFromBegin());
assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin());
assertEquals(0, pageBriefModel.getThroughputThisTime());
}
@Test
public void testTwoForCountFromBegin() {
this.testOneWithZeroCountThisTimeForAverage();
this.getStatistics().add(
buildAgentPageBriefModel(1, 2, 0, 200, 200, 200, 190, 200));
ScriptPageBriefModel pageBriefModel = (ScriptPageBriefModel) this
.getStatistics().getStatistics();
assertEquals(0, pageBriefModel.getAverageResponseTimeThisTime());
assertEquals(2, pageBriefModel.getCountFromBegin());
}
@Test
public void testThree() {
for (AgentPageBriefModel agentPageBriefModel : makePageBriefModels(3)) {
this.getStatistics().add(agentPageBriefModel);
}
ScriptPageBriefModel scriptPageBriefModel = (ScriptPageBriefModel) this
.getStatistics().getStatistics();
assertEquals(9, scriptPageBriefModel.getCountFromBegin());
assertEquals(220, scriptPageBriefModel.getLatestResponseTime());
assertEquals(220, scriptPageBriefModel.getMaxResponseTimeFromBegin());
assertEquals(180, scriptPageBriefModel.getMinResponseTimeFromBegin());
assertEquals(0, scriptPageBriefModel.getThroughputThisTime());
assertEquals(1230 / 6,
scriptPageBriefModel.getAverageResponseTimeThisTime());
}
private List<AgentPageBriefModel> makePageBriefModels(int count) {
List<AgentPageBriefModel> result = new ArrayList<AgentPageBriefModel>();
for (int i = 0; i < count; i++) {
result.add(buildAgentPageBriefModel(2, i + 2, i + 1, 200 + 10 * i,
200 + 10 * i, 200 - 10 * i, 200 + 20 * i, 400 + 10 * i));
}
return result;
}
private AgentPageBriefModel buildAgentPageBriefModel(int pageId,
long countFromBegin, long countThisTime,
long latestTimeResponseTime, long maxResponseTimeFromBegin,
long minResponseTimeFromBegin, long timeFrame,
long totalResponseTimeThisTime) {
AgentPageBriefModel result = new AgentPageBriefModel();
result.setPageId(pageId);
result.setCountFromBegin(countFromBegin);
result.setCountThisTime(countThisTime);
result.setLatestResponseTime(latestTimeResponseTime);
result.setMaxResponseTimeFromBegin(maxResponseTimeFromBegin);
result.setMinResponseTimeFromBegin(minResponseTimeFromBegin);
result.setTimeFrame(timeFrame);
result.setTotalResponseTimeThisTime(totalResponseTimeThisTime);
return result;
}
}
package org.bench4q.master.test.datastatistics;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
import org.bench4q.master.domain.valueobject.datastatistics.PageBriefStatistics;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.bench4q.share.models.master.statistics.ScriptPageBriefModel;
import org.junit.Test;
public class TestPageBrief {
private PageBriefStatistics statistics;
private PageBriefStatistics getStatistics() {
return statistics;
}
private void setStatistics(PageBriefStatistics statistics) {
this.statistics = statistics;
}
public TestPageBrief() {
this.setStatistics(new PageBriefStatistics());
}
@Test
public void testNull() {
this.getStatistics().add(null);
ScriptPageBriefModel scriptPageBriefModel = (ScriptPageBriefModel) this
.getStatistics().getStatistics();
assertTrue(scriptPageBriefModel != null);
assertEquals(0, scriptPageBriefModel.getCountFromBegin());
assertEquals(Long.MIN_VALUE,
scriptPageBriefModel.getMaxResponseTimeFromBegin());
assertEquals(Long.MAX_VALUE,
scriptPageBriefModel.getMinResponseTimeFromBegin());
assertEquals(0, scriptPageBriefModel.getAverageResponseTimeThisTime());
assertEquals(0, scriptPageBriefModel.getLatestResponseTime());
}
@Test
public void testOneWithZeroCountThisTimeForAverage() {
this.getStatistics().add(
buildAgentPageBriefModel(1, 1, 0, 200, 200, 200, 190, 0));
ScriptPageBriefModel pageBriefModel = (ScriptPageBriefModel) this
.getStatistics().getStatistics();
assertEquals(0, pageBriefModel.getAverageResponseTimeThisTime());
assertEquals(1, pageBriefModel.getCountFromBegin());
assertEquals(200, pageBriefModel.getLatestResponseTime());
assertEquals(200, pageBriefModel.getMaxResponseTimeFromBegin());
assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin());
assertEquals(0, pageBriefModel.getThroughputThisTime());
}
@Test
public void testTwoForCountFromBegin() {
this.testOneWithZeroCountThisTimeForAverage();
this.getStatistics().add(
buildAgentPageBriefModel(1, 2, 0, 200, 200, 200, 190, 200));
ScriptPageBriefModel pageBriefModel = (ScriptPageBriefModel) this
.getStatistics().getStatistics();
assertEquals(0, pageBriefModel.getAverageResponseTimeThisTime());
assertEquals(2, pageBriefModel.getCountFromBegin());
}
@Test
public void testThree() {
for (AgentPageBriefModel agentPageBriefModel : makePageBriefModels(3)) {
this.getStatistics().add(agentPageBriefModel);
}
ScriptPageBriefModel scriptPageBriefModel = (ScriptPageBriefModel) this
.getStatistics().getStatistics();
assertEquals(9, scriptPageBriefModel.getCountFromBegin());
assertEquals(220, scriptPageBriefModel.getLatestResponseTime());
assertEquals(220, scriptPageBriefModel.getMaxResponseTimeFromBegin());
assertEquals(180, scriptPageBriefModel.getMinResponseTimeFromBegin());
assertEquals(0, scriptPageBriefModel.getThroughputThisTime());
assertEquals(1230 / 6,
scriptPageBriefModel.getAverageResponseTimeThisTime());
}
private List<AgentPageBriefModel> makePageBriefModels(int count) {
List<AgentPageBriefModel> result = new ArrayList<AgentPageBriefModel>();
for (int i = 0; i < count; i++) {
result.add(buildAgentPageBriefModel(2, i + 2, i + 1, 200 + 10 * i,
200 + 10 * i, 200 - 10 * i, 200 + 20 * i, 400 + 10 * i));
}
return result;
}
private AgentPageBriefModel buildAgentPageBriefModel(int pageId,
long countFromBegin, long countThisTime,
long latestTimeResponseTime, long maxResponseTimeFromBegin,
long minResponseTimeFromBegin, long timeFrame,
long totalResponseTimeThisTime) {
AgentPageBriefModel result = new AgentPageBriefModel();
result.setPageId(pageId);
result.setCountFromBegin(countFromBegin);
result.setCountThisTime(countThisTime);
result.setLatestResponseTime(latestTimeResponseTime);
result.setMaxResponseTimeFromBegin(maxResponseTimeFromBegin);
result.setMinResponseTimeFromBegin(minResponseTimeFromBegin);
result.setTimeFrame(timeFrame);
result.setTotalResponseTimeThisTime(totalResponseTimeThisTime);
return result;
}
}

View File

@ -1,96 +1,96 @@
package org.bench4q.master.test.datastatistics;
import java.util.ArrayList;
import java.util.List;
import org.bench4q.master.domain.valueobject.datastatistics.PagesBriefStatistics;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.bench4q.share.models.agent.statistics.AgentPagesBriefModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test_PagesBrief {
private PagesBriefStatistics pagesBriefStatistics = new PagesBriefStatistics();
@Test
public void testAddNull() {
pagesBriefStatistics.add(null);
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) pagesBriefStatistics
.getStatistics();
assertEquals(0, scriptPagesBriefModel.getScriptPageBriefModels().size());
}
@Test
public void testAddOneWithOnePage() {
pagesBriefStatistics.add(createAPagesBriefModel(1));
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) pagesBriefStatistics
.getStatistics();
assertNotNull(scriptPagesBriefModel);
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(0)
.getMaxResponseTimeFromBegin());
}
private AgentPagesBriefModel createAPagesBriefModel(int size) {
AgentPagesBriefModel agentPagesBriefModel = new AgentPagesBriefModel();
List<AgentPageBriefModel> pageBriefModels = new ArrayList<AgentPageBriefModel>();
for (int i = 0; i < size; i++) {
AgentPageBriefModel pageBriefModel = new AgentPageBriefModel();
pageBriefModel.setCountFromBegin(100);
pageBriefModel.setCountThisTime(20);
pageBriefModel.setLatestResponseTime(200);
pageBriefModel.setMaxResponseTimeFromBegin(220);
pageBriefModel.setMinResponseTimeFromBegin(200);
pageBriefModel.setPageId(i);
pageBriefModel.setTimeFrame(100);
pageBriefModel.setTotalResponseTimeThisTime(20000);
pageBriefModels.add(pageBriefModel);
}
agentPagesBriefModel.setPageBriefModels(pageBriefModels);
return agentPagesBriefModel;
}
@Test
public void testAddOneWithTwoPages() {
this.pagesBriefStatistics.add(createAPagesBriefModel(2));
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) this.pagesBriefStatistics
.getStatistics();
assertEquals(2, scriptPagesBriefModel.getScriptPageBriefModels().size());
assertNotNull(scriptPagesBriefModel.getScriptPageBriefModels().get(0));
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(0)
.getMaxResponseTimeFromBegin());
assertNotNull(scriptPagesBriefModel.getScriptPageBriefModels().get(1));
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(1)
.getMaxResponseTimeFromBegin());
}
@Test
public void testAddTwoWithOnePage() {
this.pagesBriefStatistics.add(createAPagesBriefModel(1));
this.pagesBriefStatistics.add(createAPagesBriefModel(1));
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) this.pagesBriefStatistics
.getStatistics();
assertNotNull(scriptPagesBriefModel.getScriptPageBriefModels().get(0));
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(0)
.getMaxResponseTimeFromBegin());
assertEquals(1, scriptPagesBriefModel.getScriptPageBriefModels().size());
}
@Test
public void testAddTwoWithTwoPages() {
this.pagesBriefStatistics.add(createAPagesBriefModel(2));
this.pagesBriefStatistics.add(createAPagesBriefModel(2));
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) this.pagesBriefStatistics
.getStatistics();
assertNotNull(scriptPagesBriefModel.getScriptPageBriefModels().get(0));
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(0)
.getMaxResponseTimeFromBegin());
assertEquals(2, scriptPagesBriefModel.getScriptPageBriefModels().size());
}
}
package org.bench4q.master.test.datastatistics;
import java.util.ArrayList;
import java.util.List;
import org.bench4q.master.domain.valueobject.datastatistics.PagesBriefStatistics;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.bench4q.share.models.agent.statistics.AgentPagesBriefModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
import org.junit.Test;
import static org.junit.Assert.*;
public class Test_PagesBrief {
private PagesBriefStatistics pagesBriefStatistics = new PagesBriefStatistics();
@Test
public void testAddNull() {
pagesBriefStatistics.add(null);
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) pagesBriefStatistics
.getStatistics();
assertEquals(0, scriptPagesBriefModel.getScriptPageBriefModels().size());
}
@Test
public void testAddOneWithOnePage() {
pagesBriefStatistics.add(createAPagesBriefModel(1));
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) pagesBriefStatistics
.getStatistics();
assertNotNull(scriptPagesBriefModel);
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(0)
.getMaxResponseTimeFromBegin());
}
private AgentPagesBriefModel createAPagesBriefModel(int size) {
AgentPagesBriefModel agentPagesBriefModel = new AgentPagesBriefModel();
List<AgentPageBriefModel> pageBriefModels = new ArrayList<AgentPageBriefModel>();
for (int i = 0; i < size; i++) {
AgentPageBriefModel pageBriefModel = new AgentPageBriefModel();
pageBriefModel.setCountFromBegin(100);
pageBriefModel.setCountThisTime(20);
pageBriefModel.setLatestResponseTime(200);
pageBriefModel.setMaxResponseTimeFromBegin(220);
pageBriefModel.setMinResponseTimeFromBegin(200);
pageBriefModel.setPageId(i);
pageBriefModel.setTimeFrame(100);
pageBriefModel.setTotalResponseTimeThisTime(20000);
pageBriefModels.add(pageBriefModel);
}
agentPagesBriefModel.setPageBriefModels(pageBriefModels);
return agentPagesBriefModel;
}
@Test
public void testAddOneWithTwoPages() {
this.pagesBriefStatistics.add(createAPagesBriefModel(2));
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) this.pagesBriefStatistics
.getStatistics();
assertEquals(2, scriptPagesBriefModel.getScriptPageBriefModels().size());
assertNotNull(scriptPagesBriefModel.getScriptPageBriefModels().get(0));
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(0)
.getMaxResponseTimeFromBegin());
assertNotNull(scriptPagesBriefModel.getScriptPageBriefModels().get(1));
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(1)
.getMaxResponseTimeFromBegin());
}
@Test
public void testAddTwoWithOnePage() {
this.pagesBriefStatistics.add(createAPagesBriefModel(1));
this.pagesBriefStatistics.add(createAPagesBriefModel(1));
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) this.pagesBriefStatistics
.getStatistics();
assertNotNull(scriptPagesBriefModel.getScriptPageBriefModels().get(0));
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(0)
.getMaxResponseTimeFromBegin());
assertEquals(1, scriptPagesBriefModel.getScriptPageBriefModels().size());
}
@Test
public void testAddTwoWithTwoPages() {
this.pagesBriefStatistics.add(createAPagesBriefModel(2));
this.pagesBriefStatistics.add(createAPagesBriefModel(2));
ScriptPagesBriefModel scriptPagesBriefModel = (ScriptPagesBriefModel) this.pagesBriefStatistics
.getStatistics();
assertNotNull(scriptPagesBriefModel.getScriptPageBriefModels().get(0));
assertEquals(220,
scriptPagesBriefModel.getScriptPageBriefModels().get(0)
.getMaxResponseTimeFromBegin());
assertEquals(2, scriptPagesBriefModel.getScriptPageBriefModels().size());
}
}

View File

@ -1,65 +1,65 @@
package org.bench4q.master.test.domain.testPlan;
import static org.junit.Assert.*;
import javax.xml.bind.JAXBException;
import org.bench4q.master.domain.entity.TestPlan;
import org.bench4q.master.domain.entity.TestPlanScript;
import org.bench4q.master.domain.valueobject.datastatistics.RunningScriptSampler;
import org.bench4q.master.test.TestBase_MakeUpTestPlan;
import org.bench4q.share.models.master.statistics.ScriptResultModel;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_RunningScriptSampler extends TestBase_MakeUpTestPlan {
private RunningScriptSampler runningScriptSampler;
private RunningScriptSampler getRunningScriptSampler() {
return runningScriptSampler;
}
private void setRunningScriptSampler(
RunningScriptSampler runningScriptSampler) {
this.runningScriptSampler = runningScriptSampler;
}
@Before
public void prepare() {
prepareForTestPlanRunning();
this.submitATestPlanWithOneScript();
TestPlan testPlan = fetchTestPlan();
testPlan.run();
this.getTestPlanRepository().updateEntity(testPlan);
TestPlan testPlanInRunning = fetchTestPlan();
TestPlanScript testPlanScript = testPlanInRunning
.extracSpecifiedScript(getScriptId());
this.setRunningScriptSampler(new RunningScriptSampler(testPlanScript
.getRunningAgentsDB()));
}
@After
public void cleanUp() {
cleanUpForTestPlanRunning();
}
@Test
public void testGetScriptResult() throws InterruptedException, JAXBException {
ScriptResultModel scriptResultModel = this.getRunningScriptSampler()
.getResultModelFromAgent();
Thread.sleep(1000);
assertNotNull(scriptResultModel);
assertTrue(scriptResultModel.getScriptBehaviorsBriefModel()
.getTestBehaviorsBriefModel().getBehaviorBriefModels().size() > 0);
assertNotNull(scriptResultModel.getScriptBriefResultModel());
assertTrue(scriptResultModel.getScriptPagesBriefModel()
.getScriptPageBriefModels().size() >0);
}
}
package org.bench4q.master.test.domain.testPlan;
import static org.junit.Assert.*;
import javax.xml.bind.JAXBException;
import org.bench4q.master.domain.entity.TestPlan;
import org.bench4q.master.domain.entity.TestPlanScript;
import org.bench4q.master.domain.valueobject.datastatistics.RunningScriptSampler;
import org.bench4q.master.test.TestBase_MakeUpTestPlan;
import org.bench4q.share.models.master.statistics.ScriptResultModel;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_RunningScriptSampler extends TestBase_MakeUpTestPlan {
private RunningScriptSampler runningScriptSampler;
private RunningScriptSampler getRunningScriptSampler() {
return runningScriptSampler;
}
private void setRunningScriptSampler(
RunningScriptSampler runningScriptSampler) {
this.runningScriptSampler = runningScriptSampler;
}
@Before
public void prepare() {
prepareForTestPlanRunning();
this.submitATestPlanWithOneScript();
TestPlan testPlan = fetchTestPlan();
testPlan.run();
this.getTestPlanRepository().updateEntity(testPlan);
TestPlan testPlanInRunning = fetchTestPlan();
TestPlanScript testPlanScript = testPlanInRunning
.extracSpecifiedScript(getScriptId());
this.setRunningScriptSampler(new RunningScriptSampler(testPlanScript
.getRunningAgentsDB()));
}
@After
public void cleanUp() {
cleanUpForTestPlanRunning();
}
@Test
public void testGetScriptResult() throws InterruptedException, JAXBException {
ScriptResultModel scriptResultModel = this.getRunningScriptSampler()
.getResultModelFromAgent();
Thread.sleep(1000);
assertNotNull(scriptResultModel);
assertTrue(scriptResultModel.getScriptBehaviorsBriefModel()
.getTestBehaviorsBriefModel().getBehaviorBriefModels().size() > 0);
assertNotNull(scriptResultModel.getScriptBriefResultModel());
assertTrue(scriptResultModel.getScriptPagesBriefModel()
.getScriptPageBriefModels().size() >0);
}
}

View File

@ -1,54 +1,54 @@
package org.bench4q.master.test.domain.testPlan;
import static org.junit.Assert.assertTrue;
import org.bench4q.master.domain.entity.Monitor;
import org.bench4q.master.domain.valueobject.datastatistics.TestMonitorSampler;
import org.bench4q.master.test.TestBase_MakeUpTestPlan;
import org.bench4q.share.models.monitor.MonitorMain;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_TestMonitorSampler extends TestBase_MakeUpTestPlan {
private TestMonitorSampler testMonitorSampler;
private Monitor monitor;
public TestMonitorSampler getTestMonitorSampler() {
return testMonitorSampler;
}
@Autowired
public void setTestMonitorSampler(TestMonitorSampler testMonitorSampler) {
this.testMonitorSampler = testMonitorSampler;
}
@Before
public void setUp() {
this.monitor = new Monitor();
monitor.setHostName("127.0.0.1");
monitor.setPort(5556);
}
@Test
public void testDoSaveResult() {
assertTrue(this.monitor.getHostName().equals("127.0.0.1"));
assertTrue(this.monitor.getPort() == 5556);
MonitorMain monitorMain = this.testMonitorSampler.getMonitorResult(
monitor.getHostName(), monitor.getPort());
Assert.assertNotNull(monitorMain);
}
@After
public void clean() {
}
}
package org.bench4q.master.test.domain.testPlan;
import static org.junit.Assert.assertTrue;
import org.bench4q.master.domain.entity.Monitor;
import org.bench4q.master.domain.valueobject.datastatistics.TestMonitorSampler;
import org.bench4q.master.test.TestBase_MakeUpTestPlan;
import org.bench4q.share.models.monitor.MonitorMain;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_TestMonitorSampler extends TestBase_MakeUpTestPlan {
private TestMonitorSampler testMonitorSampler;
private Monitor monitor;
public TestMonitorSampler getTestMonitorSampler() {
return testMonitorSampler;
}
@Autowired
public void setTestMonitorSampler(TestMonitorSampler testMonitorSampler) {
this.testMonitorSampler = testMonitorSampler;
}
@Before
public void setUp() {
this.monitor = new Monitor();
monitor.setHostName("127.0.0.1");
monitor.setPort(5556);
}
@Test
public void testDoSaveResult() {
assertTrue(this.monitor.getHostName().equals("127.0.0.1"));
assertTrue(this.monitor.getPort() == 5556);
MonitorMain monitorMain = this.testMonitorSampler.getMonitorResult(
monitor.getHostName(), monitor.getPort());
Assert.assertNotNull(monitorMain);
}
@After
public void clean() {
}
}

View File

@ -1,54 +1,54 @@
package org.bench4q.master.test.report;
import static org.junit.Assert.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.bench4q.master.domain.service.report.ReportService;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.junit.Test;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfWriter;
public class ReportFontTest {
@Test
public void test() {
fail("Not yet implemented");
}
public void createReportTest() throws FileNotFoundException,
DocumentException {
Document document = new Document();
PdfWriter.getInstance(
document,
new FileOutputStream(ReportService.buildFilePath(UUID
.randomUUID())));
document.open();
}
public void createTestImage(UUID id, Document document) throws IOException,
Exception {
List<TimeSeries> timeSeriesList = new ArrayList<TimeSeries>();
TimeSeries timeSeries = new TimeSeries("test");
long now = System.currentTimeMillis();
timeSeries.add(new Second(new Date(now)), 3000);
timeSeries.add(new Second(new Date(now + 100)), 4000);
timeSeriesList.add(timeSeries);
ReportService.buildSeries(1, "test");
ReportService.writeImageIntoPdf(
ReportService.buildChartStream(document, 1, timeSeriesList,
"test").toByteArray(), document);
}
}
package org.bench4q.master.test.report;
import static org.junit.Assert.*;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import org.bench4q.master.domain.service.report.ReportService;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.junit.Test;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfWriter;
public class ReportFontTest {
@Test
public void test() {
fail("Not yet implemented");
}
public void createReportTest() throws FileNotFoundException,
DocumentException {
Document document = new Document();
PdfWriter.getInstance(
document,
new FileOutputStream(ReportService.buildFilePath(UUID
.randomUUID())));
document.open();
}
public void createTestImage(UUID id, Document document) throws IOException,
Exception {
List<TimeSeries> timeSeriesList = new ArrayList<TimeSeries>();
TimeSeries timeSeries = new TimeSeries("test");
long now = System.currentTimeMillis();
timeSeries.add(new Second(new Date(now)), 3000);
timeSeries.add(new Second(new Date(now + 100)), 4000);
timeSeriesList.add(timeSeries);
ReportService.buildSeries(1, "test");
ReportService.writeImageIntoPdf(
ReportService.buildChartStream(document, 1, timeSeriesList,
"test").toByteArray(), document);
}
}

View File

@ -1,42 +1,42 @@
package org.bench4q.master.test.repository;
import static org.junit.Assert.*;
import org.bench4q.master.domain.entity.Agent;
import org.bench4q.master.domain.repository.AgentRepository;
import org.bench4q.master.domain.service.AgentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_AgentRepository {
private AgentRepository agentRepoitory;
private AgentRepository getAgentRepoitory() {
return agentRepoitory;
}
@Autowired
private void setAgentRepoitory(AgentRepository agentRepoitory) {
this.agentRepoitory = agentRepoitory;
}
@Test
public void testAddAgent() {
String hostNameForTest = "133.133.12.95";
int portForTest = 6565;
assertTrue(this.getAgentRepoitory().attach(
Agent.createAgentWithoutId(hostNameForTest, portForTest)));
Agent agent = this.getAgentRepoitory().getAgentBy(hostNameForTest);
assertNotNull(agent);
assertEquals(hostNameForTest, agent.getHostName());
assertEquals(portForTest, agent.getPort());
assertEquals(500, agent.getMaxLoad());
assertEquals(AgentService.AGENT_STATUS_Idel, agent.getCurrentStatus());
assertTrue(this.getAgentRepoitory().detach(agent.getId()));
}
}
package org.bench4q.master.test.repository;
import static org.junit.Assert.*;
import org.bench4q.master.domain.entity.Agent;
import org.bench4q.master.domain.repository.AgentRepository;
import org.bench4q.master.domain.service.AgentService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_AgentRepository {
private AgentRepository agentRepoitory;
private AgentRepository getAgentRepoitory() {
return agentRepoitory;
}
@Autowired
private void setAgentRepoitory(AgentRepository agentRepoitory) {
this.agentRepoitory = agentRepoitory;
}
@Test
public void testAddAgent() {
String hostNameForTest = "133.133.12.95";
int portForTest = 6565;
assertTrue(this.getAgentRepoitory().attach(
Agent.createAgentWithoutId(hostNameForTest, portForTest)));
Agent agent = this.getAgentRepoitory().getAgentBy(hostNameForTest);
assertNotNull(agent);
assertEquals(hostNameForTest, agent.getHostName());
assertEquals(portForTest, agent.getPort());
assertEquals(500, agent.getMaxLoad());
assertEquals(AgentService.AGENT_STATUS_Idel, agent.getCurrentStatus());
assertTrue(this.getAgentRepoitory().detach(agent.getId()));
}
}

View File

@ -1,91 +1,91 @@
package org.bench4q.master.test.repository;
import static org.junit.Assert.*;
import javax.xml.bind.JAXBException;
import org.bench4q.master.domain.factory.PluginEntityFactory;
import org.bench4q.master.domain.repository.PluginRepository;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.master.test.testHelper.Test_PluginHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_PluginRepository extends Test_PluginHelper {
private PluginRepository pluginRepository;
private String pluginName;
private PluginEntityFactory pluginEntityFactory;
public PluginRepository getPluginRepository() {
return pluginRepository;
}
@Autowired
public void setPluginRepository(PluginRepository pluginRepository) {
this.pluginRepository = pluginRepository;
}
public PluginEntityFactory getPluginEntityFactory() {
return pluginEntityFactory;
}
@Autowired
public void setPluginEntityFactory(PluginEntityFactory pluginEntityFactory) {
this.pluginEntityFactory = pluginEntityFactory;
}
@Before
public void setUp() throws Bench4QException {
this.pluginName = addPlugin("ui.xml", this.pluginRepository);
}
@Test
public void testGetPlugin() {
assertNotNull(pluginName);
assertNotNull(this.getPluginRepository().getPluginUI(pluginName));
}
@Test
public void testLoadPlugins() throws Bench4QException, JAXBException {
this.clearPlugin(pluginName, this.pluginRepository);
int countBeforeInsert = this.getPluginRepository().loadPlugins().size();
System.out.println(countBeforeInsert);
String name = addPlugin("ui.xml", this.pluginRepository);
assertEquals(countBeforeInsert + 1, this.getPluginRepository()
.loadPlugins().size());
assertTrue(this.getPluginRepository().detach(name));
}
@Test
public void testLoadBehaviores() {
assertEquals(2,
this.getPluginRepository().loadBehaviorInfos(this.pluginName)
.size());
}
@Test
public void testGetPluginUI() {
assertNotNull(this.getPluginRepository().getPluginUI(pluginName));
}
@Test
public void testDeletePlugin() {
String name = addPlugin("ui.xml", this.pluginRepository);
assertTrue(this.getPluginRepository().detach(name));
}
@After
public void clear() throws Bench4QException {
this.getPluginRepository().detach(pluginName);
}
}
package org.bench4q.master.test.repository;
import static org.junit.Assert.*;
import javax.xml.bind.JAXBException;
import org.bench4q.master.domain.factory.PluginEntityFactory;
import org.bench4q.master.domain.repository.PluginRepository;
import org.bench4q.master.exception.Bench4QException;
import org.bench4q.master.test.testHelper.Test_PluginHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_PluginRepository extends Test_PluginHelper {
private PluginRepository pluginRepository;
private String pluginName;
private PluginEntityFactory pluginEntityFactory;
public PluginRepository getPluginRepository() {
return pluginRepository;
}
@Autowired
public void setPluginRepository(PluginRepository pluginRepository) {
this.pluginRepository = pluginRepository;
}
public PluginEntityFactory getPluginEntityFactory() {
return pluginEntityFactory;
}
@Autowired
public void setPluginEntityFactory(PluginEntityFactory pluginEntityFactory) {
this.pluginEntityFactory = pluginEntityFactory;
}
@Before
public void setUp() throws Bench4QException {
this.pluginName = addPlugin("ui.xml", this.pluginRepository);
}
@Test
public void testGetPlugin() {
assertNotNull(pluginName);
assertNotNull(this.getPluginRepository().getPluginUI(pluginName));
}
@Test
public void testLoadPlugins() throws Bench4QException, JAXBException {
this.clearPlugin(pluginName, this.pluginRepository);
int countBeforeInsert = this.getPluginRepository().loadPlugins().size();
System.out.println(countBeforeInsert);
String name = addPlugin("ui.xml", this.pluginRepository);
assertEquals(countBeforeInsert + 1, this.getPluginRepository()
.loadPlugins().size());
assertTrue(this.getPluginRepository().detach(name));
}
@Test
public void testLoadBehaviores() {
assertEquals(2,
this.getPluginRepository().loadBehaviorInfos(this.pluginName)
.size());
}
@Test
public void testGetPluginUI() {
assertNotNull(this.getPluginRepository().getPluginUI(pluginName));
}
@Test
public void testDeletePlugin() {
String name = addPlugin("ui.xml", this.pluginRepository);
assertTrue(this.getPluginRepository().detach(name));
}
@After
public void clear() throws Bench4QException {
this.getPluginRepository().detach(pluginName);
}
}

View File

@ -1,81 +1,81 @@
package org.bench4q.master.test.service;
import static org.junit.Assert.*;
import org.bench4q.master.infrastructure.communication.MonitorMessenger;
import org.bench4q.share.models.monitor.MemoryModel;
import org.bench4q.share.models.monitor.MonitorMain;
import org.bench4q.share.models.monitor.NetworkInterfaceModel;
import org.bench4q.share.models.monitor.PhysicalDiskModel;
import org.bench4q.share.models.monitor.ProcessModel;
import org.bench4q.share.models.monitor.ProcessorModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_MonitorMessenger {
private static final int PORT = 5556;
private static final String SUT_HOST_NAME = "133.133.12.3";
private MonitorMessenger monitorService;
private MonitorMessenger getMonitorService() {
return monitorService;
}
@Autowired
private void setMonitorService(MonitorMessenger monitorService) {
this.monitorService = monitorService;
}
@Test
public void test() {
assertNotNull(this.getMonitorService());
}
@Test
public void testphysicalDisk() {
PhysicalDiskModel logicalDiskModel = this.getMonitorService()
.physicalDisk(SUT_HOST_NAME, 5556);
assertNotNull(logicalDiskModel);
assertNotNull(logicalDiskModel.getSamplingTime());
}
@Test
public void testMemory() {
MemoryModel memoryModel = this.getMonitorService().memory(
SUT_HOST_NAME, PORT);
assertNotNull(memoryModel);
assertNotNull(memoryModel.getSamplingTime());
}
@Test
public void tesProcessor() {
ProcessorModel processorModel = this.getMonitorService().processor(
SUT_HOST_NAME, PORT);
assertNotNull(processorModel);
assertNotNull(processorModel.getSamplingTime());
}
@Test
public void testNetworkInterface() {
NetworkInterfaceModel networkInterfaceModel = this.getMonitorService()
.networkInterface(SUT_HOST_NAME, PORT);
assertNotNull(networkInterfaceModel);
assertNotNull(networkInterfaceModel.getSamplingTime());
}
@Test
public void testMonitorModel(){
MonitorMain monitorMain=this.getMonitorService().monitorModel(SUT_HOST_NAME, PORT);
assertNotNull(monitorMain);
}
@Test
public void testProcess(){
ProcessModel processModel=this.getMonitorService().process(SUT_HOST_NAME, PORT);
assertNotNull(processModel);
}
}
package org.bench4q.master.test.service;
import static org.junit.Assert.*;
import org.bench4q.master.infrastructure.communication.MonitorMessenger;
import org.bench4q.share.models.monitor.MemoryModel;
import org.bench4q.share.models.monitor.MonitorMain;
import org.bench4q.share.models.monitor.NetworkInterfaceModel;
import org.bench4q.share.models.monitor.PhysicalDiskModel;
import org.bench4q.share.models.monitor.ProcessModel;
import org.bench4q.share.models.monitor.ProcessorModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_MonitorMessenger {
private static final int PORT = 5556;
private static final String SUT_HOST_NAME = "133.133.12.3";
private MonitorMessenger monitorService;
private MonitorMessenger getMonitorService() {
return monitorService;
}
@Autowired
private void setMonitorService(MonitorMessenger monitorService) {
this.monitorService = monitorService;
}
@Test
public void test() {
assertNotNull(this.getMonitorService());
}
@Test
public void testphysicalDisk() {
PhysicalDiskModel logicalDiskModel = this.getMonitorService()
.physicalDisk(SUT_HOST_NAME, 5556);
assertNotNull(logicalDiskModel);
assertNotNull(logicalDiskModel.getSamplingTime());
}
@Test
public void testMemory() {
MemoryModel memoryModel = this.getMonitorService().memory(
SUT_HOST_NAME, PORT);
assertNotNull(memoryModel);
assertNotNull(memoryModel.getSamplingTime());
}
@Test
public void tesProcessor() {
ProcessorModel processorModel = this.getMonitorService().processor(
SUT_HOST_NAME, PORT);
assertNotNull(processorModel);
assertNotNull(processorModel.getSamplingTime());
}
@Test
public void testNetworkInterface() {
NetworkInterfaceModel networkInterfaceModel = this.getMonitorService()
.networkInterface(SUT_HOST_NAME, PORT);
assertNotNull(networkInterfaceModel);
assertNotNull(networkInterfaceModel.getSamplingTime());
}
@Test
public void testMonitorModel(){
MonitorMain monitorMain=this.getMonitorService().monitorModel(SUT_HOST_NAME, PORT);
assertNotNull(monitorMain);
}
@Test
public void testProcess(){
ProcessModel processModel=this.getMonitorService().process(SUT_HOST_NAME, PORT);
assertNotNull(processModel);
}
}

View File

@ -1,104 +1,104 @@
package org.bench4q.master.test.service;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.bench4q.master.domain.repository.PluginRepository;
import org.bench4q.master.domain.service.PluginService;
import org.bench4q.master.test.testHelper.Test_PluginHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_PluginService extends Test_PluginHelper {
private PluginService pluginService;
private String pluginName;
private PluginRepository pluginRepository;
public PluginService getPluginService() {
return pluginService;
}
@Autowired
public void setPluginService(PluginService pluginService) {
this.pluginService = pluginService;
}
public PluginRepository getPluginRepository() {
return pluginRepository;
}
@Autowired
public void setPluginRepository(PluginRepository pluginRepository) {
this.pluginRepository = pluginRepository;
}
@Before
public void setUp() {
this.pluginName = "CsvProvider";
this.getPluginRepository().detach(pluginName);
}
@After
public void clear() {
}
@Test
public void test_addPlugin() {
File file = new File(filePath("ui.xml"));
String pluginContent;
try {
pluginContent = FileUtils.readFileToString(file);
assertTrue(this.getPluginService().addPlugin(pluginContent));
assertFalse(this.getPluginService().addPlugin(pluginContent));
assertTure(this.getPluginService().deletePlugin(pluginName));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void test_loadPlugins() {
int insertBefore = this.getPluginService().loadPluginUIs().size();
addPluginByString();
assertEquals(insertBefore + 1, this.getPluginService().loadPluginUIs()
.size());
this.getPluginService().deletePlugin(pluginName);
}
@Test
public void test_loadBehaviors() {
addPluginByString();
assertEquals(2,
this.getPluginService().loadBehaviorInfoModels(pluginName)
.size());
}
private void assertTure(boolean deletePlugin) {
}
private void addPluginByString() {
File file = new File(filePath("ui.xml"));
String pluginContent;
try {
pluginContent = FileUtils.readFileToString(file);
this.getPluginService().addPlugin(pluginContent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package org.bench4q.master.test.service;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.bench4q.master.domain.repository.PluginRepository;
import org.bench4q.master.domain.service.PluginService;
import org.bench4q.master.test.testHelper.Test_PluginHelper;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_PluginService extends Test_PluginHelper {
private PluginService pluginService;
private String pluginName;
private PluginRepository pluginRepository;
public PluginService getPluginService() {
return pluginService;
}
@Autowired
public void setPluginService(PluginService pluginService) {
this.pluginService = pluginService;
}
public PluginRepository getPluginRepository() {
return pluginRepository;
}
@Autowired
public void setPluginRepository(PluginRepository pluginRepository) {
this.pluginRepository = pluginRepository;
}
@Before
public void setUp() {
this.pluginName = "CsvProvider";
this.getPluginRepository().detach(pluginName);
}
@After
public void clear() {
}
@Test
public void test_addPlugin() {
File file = new File(filePath("ui.xml"));
String pluginContent;
try {
pluginContent = FileUtils.readFileToString(file);
assertTrue(this.getPluginService().addPlugin(pluginContent));
assertFalse(this.getPluginService().addPlugin(pluginContent));
assertTure(this.getPluginService().deletePlugin(pluginName));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void test_loadPlugins() {
int insertBefore = this.getPluginService().loadPluginUIs().size();
addPluginByString();
assertEquals(insertBefore + 1, this.getPluginService().loadPluginUIs()
.size());
this.getPluginService().deletePlugin(pluginName);
}
@Test
public void test_loadBehaviors() {
addPluginByString();
assertEquals(2,
this.getPluginService().loadBehaviorInfoModels(pluginName)
.size());
}
private void assertTure(boolean deletePlugin) {
}
private void addPluginByString() {
File file = new File(filePath("ui.xml"));
String pluginContent;
try {
pluginContent = FileUtils.readFileToString(file);
this.getPluginService().addPlugin(pluginContent);
} catch (Exception e) {
e.printStackTrace();
}
}
}

View File

@ -1,41 +1,41 @@
package org.bench4q.master.test.service;
import static org.junit.Assert.*;
import java.util.UUID;
import org.bench4q.master.domain.service.report.ReportService;
import org.bench4q.master.test.TestBase_MakeUpTestPlan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_ReportService extends TestBase_MakeUpTestPlan {
private ReportService reportService;
private ReportService getReportService() {
return reportService;
}
@Autowired
private void setReportService(ReportService reportService) {
this.reportService = reportService;
}
@Test
public void testIsReportCreatedWhenActuallyNotCreated() {
submitATestPlanWithOneScript();
assertFalse(this.getReportService().isReportCreated(
getTestPlanRunIdUuid()));
}
@Test
public void testCreateReport() {
this.getReportService().createReport(
UUID.fromString("a75b14de-d99a-49ad-80b8-6ad6078ae726"));
}
}
package org.bench4q.master.test.service;
import static org.junit.Assert.*;
import java.util.UUID;
import org.bench4q.master.domain.service.report.ReportService;
import org.bench4q.master.test.TestBase_MakeUpTestPlan;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_ReportService extends TestBase_MakeUpTestPlan {
private ReportService reportService;
private ReportService getReportService() {
return reportService;
}
@Autowired
private void setReportService(ReportService reportService) {
this.reportService = reportService;
}
@Test
public void testIsReportCreatedWhenActuallyNotCreated() {
submitATestPlanWithOneScript();
assertFalse(this.getReportService().isReportCreated(
getTestPlanRunIdUuid()));
}
@Test
public void testCreateReport() {
this.getReportService().createReport(
UUID.fromString("a75b14de-d99a-49ad-80b8-6ad6078ae726"));
}
}

View File

@ -1,48 +1,48 @@
package org.bench4q.master.test.service.auth;
import static org.junit.Assert.*;
import org.bench4q.master.domain.service.auth.AccessToken;
import org.bench4q.master.domain.service.auth.AuthenticationManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_AuthenticationManager {
private AuthenticationManager authenticationManager;
private AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
@Autowired
private void setAuthenticationManager(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Test
public void test() {
assertNotNull(this.getAuthenticationManager());
}
@Test
public void testGenerateCredential() {
String generateCredential = this.getAuthenticationManager()
.generateCredential("admin");
assertNotNull(generateCredential);
System.out.println(generateCredential);
}
@Test
public void GenerateAccessToken() {
AccessToken accessToken = this.getAuthenticationManager()
.generateAccessToken("chen");
assertNotNull(accessToken);
System.out.println(accessToken.getExpiresIn());
}
}
package org.bench4q.master.test.service.auth;
import static org.junit.Assert.*;
import org.bench4q.master.domain.service.auth.AccessToken;
import org.bench4q.master.domain.service.auth.AuthenticationManager;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:service-test-context.xml" })
public class Test_AuthenticationManager {
private AuthenticationManager authenticationManager;
private AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
@Autowired
private void setAuthenticationManager(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Test
public void test() {
assertNotNull(this.getAuthenticationManager());
}
@Test
public void testGenerateCredential() {
String generateCredential = this.getAuthenticationManager()
.generateCredential("admin");
assertNotNull(generateCredential);
System.out.println(generateCredential);
}
@Test
public void GenerateAccessToken() {
AccessToken accessToken = this.getAuthenticationManager()
.generateAccessToken("chen");
assertNotNull(accessToken);
System.out.println(accessToken.getExpiresIn());
}
}

View File

@ -1,14 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:component-scan
base-package="org.bench4q.master.helper, org.bench4q.master.domain.repository, org.bench4q.master.domain.entity" />
<mvc:annotation-driven />
<task:annotation-driven />
</beans>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<context:component-scan
base-package="org.bench4q.master.helper, org.bench4q.master.domain.repository, org.bench4q.master.domain.entity" />
<mvc:annotation-driven />
<task:annotation-driven />
</beans>