Merge remote-tracking branch 'bench4qmaster/master' into web

This commit is contained in:
rkasdf 2013-08-21 20:04:28 +08:00
commit 22699d7575
110 changed files with 9574 additions and 0 deletions

4
.gitignore vendored Normal file
View File

@ -0,0 +1,4 @@
.project
.classpath
/.settings
/target

4
README.md Normal file
View File

@ -0,0 +1,4 @@
Bench4Q-Master
==============
Master Node of Bench4Q

25
descriptor.xml Normal file
View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>publish</id>
<formats>
<format>tar.gz</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
<useProjectArtifact>false</useProjectArtifact>
<unpack>false</unpack>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
<files>
<file>
<source>target/bench4q-master.jar</source>
<outputDirectory>/</outputDirectory>
</file>
</files>
</assembly>

148
pom.xml Normal file
View File

@ -0,0 +1,148 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.bench4q</groupId>
<artifactId>bench4q-master</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Bench4Q Master</name>
<description>Bench4Q Master</description>
<organization>
<name>TCSE, ISCAS</name>
</organization>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>8.1.11.v20130520</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>8.1.11.v20130520</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.12</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.0.Beta3</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.0.Draft-16</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>maxq</groupId>
<artifactId>maxq</artifactId>
<version>0.94</version>
</dependency>
<dependency>
<groupId>org.httpunit</groupId>
<artifactId>httpunit</artifactId>
<version>1.7.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j</artifactId>
<version>2.0-beta7</version>
<type>pom</type>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>org.python</groupId>
<artifactId>jython</artifactId>
<version>2.7-b1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>1.8.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>org.bench4q.master.Main</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<id>make-zip</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
<configuration>
<descriptors>
<descriptor>descriptor.xml</descriptor>
</descriptors>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
</plugins>
<finalName>bench4q-master</finalName>
</build>
</project>

View File

@ -0,0 +1,8 @@
package org.bench4q.master;
public class Main {
public static void main(String[] args) {
MasterServer masterServer = new MasterServer(8080);
masterServer.start();
}
}

View File

@ -0,0 +1,82 @@
package org.bench4q.master;
import org.bench4q.master.service.AgentService;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.DispatcherServlet;
public class MasterServer {
private Server server;
private int port;
private AgentService agentPoolService = new AgentService();
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 AgentService getAgentPoolService() {
return agentPoolService;
}
@Autowired
public void setAgentPoolService(AgentService agentPoolService) {
this.agentPoolService = agentPoolService;
}
public boolean start() {
try {
this.setServer(new Server());
Connector connector = new SocketConnector();
connector.setPort(this.getPort());
this.getServer().addConnector(connector);
ServletContextHandler servletContextHandler = new ServletContextHandler();
ServletHolder servletHolder = servletContextHandler.addServlet(
DispatcherServlet.class, "/");
servletHolder
.setInitParameter("contextConfigLocation",
"classpath*:org/bench4q/master/config/application-context.xml");
this.getServer().setHandler(servletContextHandler);
this.getServer().start();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean stop() {
try {
if (this.getServer() != null) {
this.getServer().stop();
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
this.setServer(null);
}
}
}

View File

@ -0,0 +1,93 @@
package org.bench4q.master.api;
import java.util.List;
import org.bench4q.master.api.model.AgentResponseModel;
import org.bench4q.master.communication.AgentStateService;
import org.bench4q.master.entity.db.Agent;
import org.bench4q.master.service.AgentService;
import org.bench4q.master.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;
@Controller
@RequestMapping("/agentManage")
public class AgentController extends BaseController {
private AgentService agentPoolService = new AgentService();
private AgentStateService agentStateService = new AgentStateService();
public AgentStateService getAgentStateService() {
return agentStateService;
}
@Autowired
public void setAgentStateService(AgentStateService agentStateService) {
this.agentStateService = agentStateService;
}
public AgentService getAgentPoolService() {
return agentPoolService;
}
@Autowired
private void setAgentPoolService(AgentService agentPoolService) {
this.agentPoolService = agentPoolService;
}
@RequestMapping(value = "/addAgentToPool", method = RequestMethod.POST)
@ResponseBody
public AgentResponseModel addAgentToPool(@RequestBody Agent agent) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _setAgentResponseModel(false,
"you don't have the power to add agent to pool!", null);
}
synchronized (this.getAgentPoolService().getAgentLock()) {
if (!this.getAgentPoolService().addAgentToPool(agent)) {
return _setAgentResponseModel(false,
"add agent to DB fails in addAgentToPool", null);
}
this.getAgentPoolService().getAgentLock().notifyAll();
return _setAgentResponseModel(true, "", null);
}
}
@RequestMapping(value = "/removeAgentFromPool", method = RequestMethod.GET)
@ResponseBody
public AgentResponseModel removeAgentFromPool(@RequestParam String hostName) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _setAgentResponseModel(false,
"you don't have the power to remove agent from pool!", null);
}
synchronized (this.getAgentPoolService().getAgentLock()) {
if (!this.getAgentPoolService().removeAgentFromPool(hostName)) {
return _setAgentResponseModel(false,
"remove agent from DB fails in removeAgentFromPool",
null);
}
return this._setAgentResponseModel(true, "", null);
}
}
@RequestMapping(value = "/queryAgentList", method = RequestMethod.POST)
@ResponseBody
public AgentResponseModel queryAgentList() {
List<Agent> list = this.getAgentPoolService().loadAgentPoolFromDB();
return _setAgentResponseModel(true, "", list);
}
private AgentResponseModel _setAgentResponseModel(boolean isSuccess,
String failCauseString, List<Agent> agents) {
AgentResponseModel agentResponseModel = new AgentResponseModel();
agentResponseModel.setSuccess(isSuccess);
agentResponseModel.setFailCauseString(failCauseString);
agentResponseModel.setAgents(agents);
return agentResponseModel;
}
}

View File

@ -0,0 +1,41 @@
package org.bench4q.master.api;
import javax.servlet.http.HttpServletRequest;
import org.bench4q.master.auth.AuthenticationManager;
import org.bench4q.master.entity.db.User;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class BaseController {
private HttpServletRequest request;
private AuthenticationManager authenticationManager;
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;
}
protected User getPrincipal() {
return this.getAuthenticationManager().getPrincipal(this.getRequest());
}
protected boolean checkScope(byte scope) {
return this.getAuthenticationManager().checkScope(this.getRequest(),
scope);
}
}

View File

@ -0,0 +1,24 @@
package org.bench4q.master.api;
import org.bench4q.master.entity.db.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

@ -0,0 +1,85 @@
package org.bench4q.master.api;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.bench4q.master.api.model.MonitorResponseModel;
import org.bench4q.master.communication.HttpRequester;
import org.bench4q.master.communication.HttpRequester.HttpResponse;
import org.bench4q.master.communication.monitor.LogicalDiskModel;
import org.bench4q.master.service.UserService;
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(value = "/monitorController")
public class MonitorController extends BaseController {
private HttpRequester httpRequester;
public HttpRequester getHttpRequester() {
return httpRequester;
}
@Autowired
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
@RequestMapping(value = "/logicDiskMonitorSUTInfo", method = RequestMethod.GET)
@ResponseBody
public MonitorResponseModel logicDiskMonitorSUTInfo(@RequestParam String url) {
try {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return _setResponseModel(false,
"you don't have the power to check the monitor", null);
}
HttpResponse httpResponse = this.getHttpRequester().sendGet(url,
null, null);
if (httpResponse == null) {
return null;
}
LogicalDiskModel logicalModel = _extractModel(httpResponse);
if (logicalModel == null) {
return null;
}
return _setResponseModel(true, "", logicalModel);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private MonitorResponseModel _setResponseModel(boolean success,
String failCause, LogicalDiskModel logicalDiskModel) {
MonitorResponseModel result = new MonitorResponseModel();
result.setSuccess(success);
result.setFailCause(failCause);
result.setLogicalDiskModel(logicalDiskModel);
return result;
}
private LogicalDiskModel _extractModel(HttpResponse httpResponse) {
LogicalDiskModel result = new LogicalDiskModel();
Unmarshaller unmarshaller;
try {
unmarshaller = JAXBContext.newInstance(result.getClass())
.createUnmarshaller();
result = (LogicalDiskModel) unmarshaller
.unmarshal(new ByteArrayInputStream(httpResponse
.getContent().getBytes()));
return result;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,89 @@
package org.bench4q.master.api;
import java.util.List;
import org.bench4q.master.api.model.OrganizeRecordPortResponseModel;
import org.bench4q.master.entity.db.Port;
import org.bench4q.master.service.PortPoolService;
import org.bench4q.master.service.UserService;
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)
@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!", null);
}
if (!this.getPortPoolService().addPortToDBPool(port)) {
return _buildResponseModel(false, "add to DB pool fails", null);
}
return _buildResponseModel(true, "", null);
}
@RequestMapping(value = "/removePortFromPool", method = RequestMethod.POST)
@ResponseBody
public OrganizeRecordPortResponseModel removePortFromPool(
@RequestParam int port) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false,
"you don't hava the power to remove port from pool!", null);
}
if (!this.getPortPoolService().removePortFromDBPool(port)) {
return _buildResponseModel(false, "remove from local fails", null);
}
return _buildResponseModel(true, "", null);
}
@RequestMapping(value = "/loadPortList", method = RequestMethod.POST)
@ResponseBody
public OrganizeRecordPortResponseModel loadPortList(@RequestParam int port) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return _buildResponseModel(false,
"you don't hava the power to add port to pool!", null);
}
return this._buildResponseModel(true, "",
this.portPoolService.loadPortList());
}
private OrganizeRecordPortResponseModel _buildResponseModel(
boolean success, String failString, List<Port> ports) {
OrganizeRecordPortResponseModel result = new OrganizeRecordPortResponseModel();
result.setSuccess(success);
result.setFailCauseString(failString);
result.setPorts(ports);
return result;
}
}

View File

@ -0,0 +1,145 @@
package org.bench4q.master.api;
import java.io.File;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;
import org.bench4q.master.api.model.OperateScriptServerResponseModel;
import org.bench4q.master.entity.ScriptCapturer;
import org.bench4q.master.entity.db.Port;
import org.bench4q.master.entity.db.Script;
import org.bench4q.master.service.PortPoolService;
import org.bench4q.master.service.ScriptService;
import org.bench4q.master.service.UserService;
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("/RecordScript")
public class ScriptController extends BaseController {
private int _portForRecord;
private ScriptCapturer scriptCapturer = null;
private ScriptService scriptService;
private PortPoolService _portPoolService = new PortPoolService();
private static final Object PORT_LOCK = new Object();
private void setPortForRecord(int portForRecord) {
this._portForRecord = portForRecord;
}
@Autowired
public void setScriptCapturer(ScriptCapturer scriptCapturer) {
this.scriptCapturer = scriptCapturer;
}
@Autowired
public void setScriptService(ScriptService scriptService) {
this.scriptService = scriptService;
}
@Autowired
public void setPortPoolService(PortPoolService portPoolService) {
this._portPoolService = portPoolService;
}
@RequestMapping(value = "/startScriptRecordServer", method = 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);
}
synchronized (PORT_LOCK) {
Port port = this._portPoolService.getAPortNotInUse();
if (port == null) {
return _buildReponseModel(false, "port is in use!", "", -1,
null);
}
this.setPortForRecord(port.getPort());
}
this.scriptCapturer = new ScriptCapturer(this._portForRecord,
System.getProperty("user.dir") + File.separator, this
.getPrincipal().getUserName());
scriptCapturer.startCurrentRecord();
return _buildReponseModel(true, "",
this.scriptCapturer.getIpHttpCaptureServerAdress(),
this.scriptCapturer.getPortForRecord(), null);
}
@RequestMapping(value = "/stopScriptRecordServer", method = RequestMethod.POST)
@ResponseBody
public OperateScriptServerResponseModel stopScriptRecordServer() {
if (!checkScope(UserService.NORAML_AUTHENTICATION)) {
return _buildReponseModel(false,
"has no power for stopScriptCapture!!!", "", -1, null);
}
if (this.scriptCapturer == null) {
return _buildReponseModel(false,
"there is no RecordingServer to stop", "", -1, null);
}
this.scriptCapturer.stopCurrentRecord();
this.scriptCapturer.shutHttpCaptureProxyServer();
this._portPoolService.backThePortToPool(this._portForRecord);
return _buildReponseModel(true, "RecordServer stop", "", -1, null);
}
@RequestMapping(value = "/saveScriptToDB", method = RequestMethod.GET)
@ResponseBody
public OperateScriptServerResponseModel saveScriptToDB(
@RequestParam String scriptName) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return _buildReponseModel(false,
"saveScriptToDB check your scope fail!", "", -1, null);
}
this.scriptService.saveScriptToDB(scriptName, this.getPrincipal()
.getId(), this.scriptCapturer.getScriptContent());
return _buildReponseModel(true, "Save to DataBase!!", "", -1, null);
}
@RequestMapping(value = "/loadScriptList", method = RequestMethod.POST)
@ResponseBody
public OperateScriptServerResponseModel loadScriptList() {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
return this._buildReponseModel(true, null, null, 0,
this.scriptService.loadScripts(this.getPrincipal()));
}
@RequestMapping(value = "/queryScriptsByDate", method = RequestMethod.POST)
@ResponseBody
public OperateScriptServerResponseModel queryScriptsByDate(
@RequestParam Date startDate, @RequestParam Date endDate) {
return this
._buildReponseModel(true, null, null, 0, this.scriptService
.queryScriptsByCreateTime(startDate, endDate));
}
private OperateScriptServerResponseModel _buildReponseModel(
boolean isSuccess, String failCauseString, String hostName,
int port, List<Script> scripts) {
OperateScriptServerResponseModel responseModel = new OperateScriptServerResponseModel();
responseModel.setSuccess(isSuccess);
responseModel.setFailCauseString(failCauseString);
responseModel.setHostName(hostName);
responseModel.setPort(port);
responseModel.setScripts(scripts);
return responseModel;
}
}

View File

@ -0,0 +1,131 @@
package org.bench4q.master.api;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.bench4q.master.api.model.AgentBriefModel;
import org.bench4q.master.api.model.AgentDetailModel;
import org.bench4q.master.api.model.RunningScriptModel;
import org.bench4q.master.api.model.TestPlanConfig;
import org.bench4q.master.api.model.TestPlanModel;
import org.bench4q.master.api.model.TestPlanResultModel;
import org.bench4q.master.service.UserService;
import org.bench4q.master.testPlan.TestPlanRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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;
@Controller
@RequestMapping("/testPlan")
public class TestPlanController extends BaseController {
private TestPlanRunner testPlanRunner;
private UserService userService;
public TestPlanRunner getTestPlanRunner() {
return testPlanRunner;
}
@Autowired
public void setTestPlanRunner(TestPlanRunner testPlanRunner) {
this.testPlanRunner = testPlanRunner;
}
public UserService getUserService() {
return userService;
}
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@RequestMapping(value = "/getAgentBriefStatus", method = RequestMethod.GET)
@ResponseBody
public AgentBriefModel getBriefStatusModelFromAgent(
@RequestParam UUID testPlanId, @RequestParam UUID agentRunId) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
return this.testPlanRunner.getBriefStatusFromAgent(testPlanId,
agentRunId);
}
@RequestMapping(value = "/runTestPlanWithScriptId", method = RequestMethod.GET)
@ResponseBody
public TestPlanResultModel runTestPlanWithScriptId(
@RequestParam int scriptId, @RequestParam int requireLoad) {
List<RunningScriptModel> list = new ArrayList<RunningScriptModel>();
// if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
// return _buildResponseModel(null);
// }
RunningScriptModel model = new RunningScriptModel();
model.setScriptId(scriptId);
model.setRequireLoad(requireLoad);
model.setAgentRunIds(new ArrayList<UUID>());
list.add(model);
TestPlanModel testPlanModel = new TestPlanModel();
testPlanModel.setRunnningScriptModels(list);
TestPlanConfig config = new TestPlanConfig();
config.setWarmUp(20);
config.setExecuteRange(50);
config.setCoolDown(10);
testPlanModel.setConfig(config);
return _buildResponseModel(this.testPlanRunner.runTestPlanWithModel(
testPlanModel, this.userService.getUserByName("chen")));
}
@RequestMapping(value = "/runTestPlanWithTestPlanModel", method = RequestMethod.POST)
@ResponseBody
public TestPlanResultModel runTestPlanWithTestPlanModel(
@RequestBody TestPlanModel testPlanModel) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return _buildResponseModel(null);
}
return _buildResponseModel(this.testPlanRunner.runTestPlanWithModel(
testPlanModel, this.getPrincipal()));
}
private TestPlanResultModel _buildResponseModel(UUID testPlanId) {
TestPlanResultModel result = new TestPlanResultModel();
result.setTestPlanId(testPlanId);
return result;
}
@RequestMapping(value = "/getRunningInfo", method = RequestMethod.GET)
@ResponseBody
public TestPlanResultModel getTestPlanRunningInfo(
@RequestParam UUID testPlanId) {
return this.testPlanRunner.queryTestPlanResultModel(testPlanId);
}
@RequestMapping(value = "/getAgentDetailStatus", method = RequestMethod.GET)
@ResponseBody
public AgentDetailModel getAgentDetailStatus(@RequestParam UUID testPlanId,
@RequestParam UUID agentRunId) {
if (!this.checkScope(UserService.NORAML_AUTHENTICATION)) {
return null;
}
return this.testPlanRunner.getDetailStatusOfAgent(testPlanId,
agentRunId);
}
@RequestMapping(value = "/getScriptRunningStatus", method = {
RequestMethod.POST, RequestMethod.GET })
@ResponseBody
public void getScriptRunningStatus(@RequestParam UUID testPlanId,
@RequestParam int scriptId) {
if (!this.checkScope(UserService.SUPER_AUTHENTICATION)) {
return;
}
// this.testPlanRunner
}
}

View File

@ -0,0 +1,75 @@
package org.bench4q.master.api;
import org.bench4q.master.api.model.AuthorizeResponseModel;
import org.bench4q.master.api.model.RegisterResponseModel;
import org.bench4q.master.auth.AccessToken;
import org.bench4q.master.auth.AuthenticationManager;
import org.bench4q.master.entity.db.User;
import org.bench4q.master.service.UserService;
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("/user")
public class UserController {
private UserService userService;
private AuthenticationManager authenticationManager;
private UserService getUserService() {
return userService;
}
@Autowired
private void setUserService(UserService userService) {
this.userService = userService;
}
public AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
@Autowired
public void setAuthenticationManager(
AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
@ResponseBody
public RegisterResponseModel register(@RequestParam String userName,
@RequestParam String password) {
boolean success = this.getUserService().register(userName, password);
RegisterResponseModel registerUserResponseModel = new RegisterResponseModel();
registerUserResponseModel.setSuccess(success);
return registerUserResponseModel;
}
@RequestMapping(value = "/authorize", method = RequestMethod.GET)
@ResponseBody
public AuthorizeResponseModel authorize(@RequestParam String userName,
@RequestParam String password) {
boolean authorized = this.getUserService().validateUser(userName,
password);
if (!authorized) {
AuthorizeResponseModel responseModel = new AuthorizeResponseModel();
responseModel.setAccessToken(null);
responseModel.setExpiresIn(-1);
responseModel.setSuccess(false);
return responseModel;
}
User user = this.getUserService().getUserByName(userName);
AccessToken accessToken = this.getAuthenticationManager()
.generateAccessToken(user);
String credential = this.getAuthenticationManager().generateCredential(
user);
AuthorizeResponseModel responseModel = new AuthorizeResponseModel();
responseModel.setAccessToken(credential);
responseModel.setExpiresIn(accessToken.getExpiresIn());
responseModel.setSuccess(true);
return responseModel;
}
}

View File

@ -0,0 +1,31 @@
package org.bench4q.master.api.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.master.communication.agent.TestBriefStatusModel;
@XmlRootElement(name = "agentBriefModel")
public class AgentBriefModel {
private boolean finish;
private TestBriefStatusModel testStatusModel;
@XmlElement(name = "finish")
public boolean isFinish() {
return finish;
}
public void setFinish(boolean finish) {
this.finish = finish;
}
@XmlElement
public TestBriefStatusModel getTestStatusModel() {
return testStatusModel;
}
public void setTestStatusModel(TestBriefStatusModel testStatusModel) {
this.testStatusModel = testStatusModel;
}
}

View File

@ -0,0 +1,30 @@
package org.bench4q.master.api.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.master.communication.agent.TestDetailStatusModel;
@XmlRootElement(name = "agentDetailModel")
public class AgentDetailModel {
private boolean finish;
private TestDetailStatusModel testStatusModel;
@XmlElement(name = "finish")
public boolean isFinish() {
return finish;
}
public void setFinish(boolean finish) {
this.finish = finish;
}
@XmlElement
public TestDetailStatusModel getTestStatusModel() {
return testStatusModel;
}
public void setTestStatusModel(TestDetailStatusModel testStatusModel) {
this.testStatusModel = testStatusModel;
}
}

View File

@ -0,0 +1,44 @@
package org.bench4q.master.api.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.master.entity.db.Agent;
@XmlRootElement(name = "agentResponse")
public class AgentResponseModel {
private boolean isSuccess;
private String failCauseString;
private List<Agent> agents;
@XmlElement
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
@XmlElement
public String getFailCauseString() {
return failCauseString;
}
public void setFailCauseString(String failCauseString) {
this.failCauseString = failCauseString;
}
@XmlElementWrapper(name = "AgentList")
@XmlElement(name = "agent")
public List<Agent> getAgents() {
return agents;
}
public void setAgents(List<Agent> agents) {
this.agents = agents;
}
}

View File

@ -0,0 +1,40 @@
package org.bench4q.master.api.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "authorizeResponse")
public class AuthorizeResponseModel {
private boolean success;
private String accessToken;
private int expiresIn;
@XmlElement
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
@XmlElement
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
@XmlElement
public int getExpiresIn() {
return expiresIn;
}
public void setExpiresIn(int expiresIn) {
this.expiresIn = expiresIn;
}
}

View File

@ -0,0 +1,41 @@
package org.bench4q.master.api.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.master.communication.monitor.LogicalDiskModel;
@XmlRootElement(name = "MonitorResponseModel")
public class MonitorResponseModel {
private boolean success;
private String failCause;
private LogicalDiskModel logicalDiskModel;
@XmlElement(name = "success")
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
@XmlElement(name = "failCause")
public String getFailCause() {
return failCause;
}
public void setFailCause(String failCause) {
this.failCause = failCause;
}
@XmlElement(name = "logicalDisk")
public LogicalDiskModel getLogicalDiskModel() {
return logicalDiskModel;
}
public void setLogicalDiskModel(LogicalDiskModel logicalDiskModel) {
this.logicalDiskModel = logicalDiskModel;
}
}

View File

@ -0,0 +1,63 @@
package org.bench4q.master.api.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.master.entity.db.Script;
@XmlRootElement(name = "OperateScriptServerResponse")
public class OperateScriptServerResponseModel {
private boolean success;
private String failCauseString;
private String hostNameString;
private int port;
private List<Script> scripts;
@XmlElement
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
@XmlElement
public String getFailCauseString() {
return failCauseString;
}
public void setFailCauseString(String failCauseString) {
this.failCauseString = failCauseString;
}
@XmlElement
public String getHostNameString() {
return hostNameString;
}
public void setHostName(String hostNameString) {
this.hostNameString = hostNameString;
}
@XmlElement
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@XmlElement
public List<Script> getScripts() {
return scripts;
}
public void setScripts(List<Script> scripts) {
this.scripts = scripts;
}
}

View File

@ -0,0 +1,44 @@
package org.bench4q.master.api.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.bench4q.master.entity.db.Port;
@XmlRootElement(name = "OperateScriptServerResponse")
public class OrganizeRecordPortResponseModel {
private boolean success;
private String failCauseString;
private List<Port> ports;
@XmlElement
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
@XmlElement
public String getFailCauseString() {
return failCauseString;
}
public void setFailCauseString(String failCauseString) {
this.failCauseString = failCauseString;
}
@XmlElementWrapper(name = "portList")
@XmlElement(name = "port")
public List<Port> getPorts() {
return ports;
}
public void setPorts(List<Port> ports) {
this.ports = ports;
}
}

View File

@ -0,0 +1,19 @@
package org.bench4q.master.api.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "registerResponse")
public class RegisterResponseModel {
private boolean success;
@XmlElement
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
}

View File

@ -0,0 +1,43 @@
package org.bench4q.master.api.model;
import java.util.List;
import java.util.UUID;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "runningScripModel")
public class RunningScriptModel {
private int scriptId;
private int requireLoad;
private List<UUID> agentRunIds;
@XmlElement
public int getScriptId() {
return scriptId;
}
public void setScriptId(int scriptId) {
this.scriptId = scriptId;
}
@XmlElement
public int getRequireLoad() {
return requireLoad;
}
public void setRequireLoad(int requireLoad) {
this.requireLoad = requireLoad;
}
@XmlElementWrapper(name = "AgentRunIdList")
@XmlElement(name = "agentRunId")
public List<UUID> getAgentRunIds() {
return agentRunIds;
}
public void setAgentRunIds(List<UUID> agentRunIds) {
this.agentRunIds = agentRunIds;
}
}

View File

@ -0,0 +1,39 @@
package org.bench4q.master.api.model;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class TestPlanConfig {
private long warmUp;
private long executeRange;
private long coolDown;
@XmlElement
public long getWarmUp() {
return warmUp;
}
public void setWarmUp(long warmUp) {
this.warmUp = warmUp;
}
@XmlElement
public long getExecuteRange() {
return executeRange;
}
public void setExecuteRange(long executeRange) {
this.executeRange = executeRange;
}
@XmlElement
public long getCoolDown() {
return coolDown;
}
public void setCoolDown(long coolDown) {
this.coolDown = coolDown;
}
}

View File

@ -0,0 +1,43 @@
package org.bench4q.master.api.model;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "testPlanModel")
public class TestPlanModel {
private TestPlanConfig config;
private String name = "";
private List<RunningScriptModel> runningScriptModels;
@XmlElement
public TestPlanConfig getConfig() {
return config;
}
public void setConfig(TestPlanConfig config) {
this.config = config;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElementWrapper(name = "runningScriptModelList")
@XmlElement(name = "runningScriptModel")
public List<RunningScriptModel> getRunnningScriptModels() {
return runningScriptModels;
}
public void setRunnningScriptModels(
List<RunningScriptModel> runningScriptModels) {
this.runningScriptModels = runningScriptModels;
}
}

View File

@ -0,0 +1,35 @@
package org.bench4q.master.api.model;
import java.util.List;
import java.util.UUID;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "RunTestPlanResultModel")
public class TestPlanResultModel {
private UUID testPlanId;
private List<RunningScriptModel> runningScriptModels;
@XmlElement(name = "testPlanId")
public UUID getTestPlanId() {
return testPlanId;
}
public void setTestPlanId(UUID testPlanId) {
this.testPlanId = testPlanId;
}
@XmlElementWrapper(name = "ContentList")
@XmlElement(name = "RunningScriptContextModel")
public List<RunningScriptModel> getRunningScriptModels() {
return runningScriptModels;
}
public void setRunningScriptModels(
List<RunningScriptModel> runningScriptContextModels) {
this.runningScriptModels = runningScriptContextModels;
}
}

View File

@ -0,0 +1,42 @@
package org.bench4q.master.api.model.TransformFromOldScriptToNewScript;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "behavior")
public class BehaviorModel {
private String id;
private List<SampleModel> sampleModelList;
private List<TimerModel> timerModelList;
@XmlAttribute(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement(name = "sample")
public List<SampleModel> getSampleModelList() {
return sampleModelList;
}
public void setSampleModelList(List<SampleModel> sampleModelList) {
this.sampleModelList = sampleModelList;
}
@XmlElement(name = "timer")
public List<TimerModel> getTimerModelList() {
return timerModelList;
}
public void setTimerModelList(List<TimerModel> timerModelList) {
this.timerModelList = timerModelList;
}
}

View File

@ -0,0 +1,30 @@
package org.bench4q.master.api.model.TransformFromOldScriptToNewScript;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "behaviors")
public class BehaviorsModel {
private PluginModel pluginModel;
private BehaviorModel behaviorModels[];
@XmlElement(name = "behavior")
public BehaviorModel[] getBehaviorModels() {
return behaviorModels;
}
public void setBehaviorModels(BehaviorModel behaviorModels[]) {
this.behaviorModels = behaviorModels;
}
@XmlElement(name = "plugins")
public PluginModel getPluginModel() {
return pluginModel;
}
public void setPluginModel(PluginModel pluginModel) {
this.pluginModel = pluginModel;
}
}

View File

@ -0,0 +1,8 @@
package org.bench4q.master.api.model.TransformFromOldScriptToNewScript;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "loadprofile")
public class LoadProfileModel {
}

View File

@ -0,0 +1,29 @@
package org.bench4q.master.api.model.TransformFromOldScriptToNewScript;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "param")
public class ParameterModel {
private String name;
private String value;
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlAttribute(name = "value")
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

View File

@ -0,0 +1,19 @@
package org.bench4q.master.api.model.TransformFromOldScriptToNewScript;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "plugins")
public class PluginModel {
private UseModel[] useModels;
@XmlElement(name = "use")
public UseModel[] getUseModels() {
return useModels;
}
public void setUseModels(UseModel[] useModels) {
this.useModels = useModels;
}
}

View File

@ -0,0 +1,42 @@
package org.bench4q.master.api.model.TransformFromOldScriptToNewScript;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "sample")
public class SampleModel {
private String use;
private String name;
private ParameterModel[] parameterModels;
@XmlAttribute(name = "use")
public String getUse() {
return use;
}
public void setUse(String use) {
this.use = use;
}
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElementWrapper(name = "params")
@XmlElement(name = "param")
public ParameterModel[] getParameterModels() {
return parameterModels;
}
public void setParameterModels(ParameterModel[] parameterModels) {
this.parameterModels = parameterModels;
}
}

View File

@ -0,0 +1,29 @@
package org.bench4q.master.api.model.TransformFromOldScriptToNewScript;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "scenario")
public class ScenarioModel {
private BehaviorsModel behaviorsModel;
private LoadProfileModel loadProfileModel;
@XmlElement(name = "behaviors")
public BehaviorsModel getBehaviorsModel() {
return behaviorsModel;
}
public void setBehaviorsModel(BehaviorsModel behaviorsModel) {
this.behaviorsModel = behaviorsModel;
}
@XmlElement(name = "loadprofile")
public LoadProfileModel getLoadProfileModel() {
return loadProfileModel;
}
public void setLoadProfileModel(LoadProfileModel loadProfileModel) {
this.loadProfileModel = loadProfileModel;
}
}

View File

@ -0,0 +1,42 @@
package org.bench4q.master.api.model.TransformFromOldScriptToNewScript;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "timer")
public class TimerModel {
private String use;
private String name;
private ParameterModel[] parameterModels;
@XmlAttribute(name = "use")
public String getUse() {
return use;
}
public void setUse(String use) {
this.use = use;
}
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElementWrapper(name = "params")
@XmlElement(name = "param")
public ParameterModel[] getParameterModels() {
return parameterModels;
}
public void setParameterModels(ParameterModel[] parameterModels) {
this.parameterModels = parameterModels;
}
}

View File

@ -0,0 +1,42 @@
package org.bench4q.master.api.model.TransformFromOldScriptToNewScript;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "use")
public class UseModel {
private String id;
private String name;
private ParameterModel[] parameters;
@XmlAttribute(name = "id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlAttribute(name = "name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElementWrapper(name = "params")
@XmlElement(name = "param")
public ParameterModel[] getParameters() {
return parameters;
}
public void setParameters(ParameterModel[] parameters) {
this.parameters = parameters;
}
}

View File

@ -0,0 +1,55 @@
package org.bench4q.master.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

@ -0,0 +1,135 @@
package org.bench4q.master.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.entity.db.User;
import org.bench4q.master.helper.StringHelper;
import org.bench4q.master.service.UserService;
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 UserService userService;
private StringHelper stringHelper;
private CryptoManager getCryptoManager() {
return cryptoManager;
}
@Autowired
private void setCryptoManager(CryptoManager cryptoManager) {
this.cryptoManager = cryptoManager;
}
private UserService getUserService() {
return userService;
}
@Autowired
private void setUserService(UserService userService) {
this.userService = userService;
}
private StringHelper getStringHelper() {
return stringHelper;
}
@Autowired
private void setStringHelper(StringHelper stringHelper) {
this.stringHelper = stringHelper;
}
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 scope) {
AccessToken accessToken = this.getAccessToken(request);
if (accessToken == null) {
return false;
}
return accessToken.getScope() >= scope;
}
public String generateCredential(User user) {
AccessToken accessToken = this.generateAccessToken(user);
return this.generateCredentialFromAccessToken(accessToken);
}
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.getUserService().getUserByName(accessToken.getUserName());
}
public 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;
}
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

@ -0,0 +1,120 @@
package org.bench4q.master.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

@ -0,0 +1,55 @@
package org.bench4q.master.communication;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.bench4q.master.communication.HttpRequester.HttpResponse;
import org.bench4q.master.communication.agent.ServerStatusModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AgentStateService {
private HttpRequester httpRequester = new HttpRequester();
public HttpRequester getHttpRequester() {
return httpRequester;
}
@Autowired
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
public ServerStatusModel askLiving(String hostName, int port) {
try {
HttpResponse httpResponse = this.getHttpRequester().sendGet(
hostName + ":" + port + "/", null, null);
if (httpResponse == null) {
return null;
}
return _extractServerStatusModel(httpResponse.getContent());
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
private ServerStatusModel _extractServerStatusModel(String content)
throws JAXBException {
ServerStatusModel resultModel = new ServerStatusModel();
Unmarshaller unmarshaller = JAXBContext.newInstance(
resultModel.getClass()).createUnmarshaller();
resultModel = (ServerStatusModel) unmarshaller
.unmarshal(new ByteArrayInputStream(content.getBytes()));
return resultModel;
}
}

View File

@ -0,0 +1,287 @@
package org.bench4q.master.communication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import org.springframework.stereotype.Component;
@Component
public class HttpRequester {
private String defaultContentEncoding;
public HttpRequester() {
this.setDefaultContentEncoding(Charset.defaultCharset().name());
}
public String getDefaultContentEncoding() {
return defaultContentEncoding;
}
public void setDefaultContentEncoding(String defaultContentEncoding) {
this.defaultContentEncoding = defaultContentEncoding;
}
public HttpResponse sendPost(String urlString, Map<String, String> params,
Map<String, String> properties) throws IOException {
return this.send(urlString, "POST", params, "", properties);
}
public HttpResponse sendPostXml(String urlString, String contentString,
Map<String, String> properties) throws IOException {
if (properties == null) {
properties = new HashMap<String, String>();
}
properties.put("Content-Type", "application/xml");
return this.send(urlString, "POST", null, contentString, properties);
}
public HttpResponse sendGet(String urlString, Map<String, String> params,
Map<String, String> properties) throws IOException {
return this.send(urlString, "GET", params, "", properties);
}
private HttpResponse send(String urlString, String method,
Map<String, String> parameters, String Content,
Map<String, String> propertys) throws IOException {
HttpURLConnection urlConnection = null;
if (method.equalsIgnoreCase("GET") && parameters != null) {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : parameters.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
String encodedValue = URLEncoder.encode(parameters.get(key),
"UTF-8");
param.append(key).append("=").append(encodedValue);
i++;
}
urlString += param;
}
if (!urlString.startsWith("http://")) {
urlString = "http://" + urlString;
}
// TODO: delete it
System.out.println(urlString);
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false);
if (propertys != null)
for (String key : propertys.keySet()) {
urlConnection.addRequestProperty(key, propertys.get(key));
}
if (method.equalsIgnoreCase("POST") && parameters != null) {
StringBuffer param = new StringBuffer();
for (String key : parameters.keySet()) {
param.append("&");
String encodedValueString = URLEncoder.encode(
parameters.get(key), "UTF-8");
param.append(key).append("=").append(encodedValueString);
}
urlConnection.getOutputStream().write(param.toString().getBytes());
urlConnection.getOutputStream().flush();
urlConnection.getOutputStream().close();
} else if (method.equalsIgnoreCase("POST") && !Content.isEmpty()) {
urlConnection.getOutputStream().write(Content.getBytes());
urlConnection.getOutputStream().flush();
urlConnection.getOutputStream().close();
}
try {
HttpResponse result = this.makeContent(urlString, urlConnection);
return result;
} catch (ConnectException e) {
return null;
}
}
private HttpResponse makeContent(String urlString,
HttpURLConnection urlConnection) throws ConnectException {
HttpResponse httpResponser = new HttpResponse();
try {
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
httpResponser.contentCollection = new Vector<String>();
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
httpResponser.contentCollection.add(line);
temp.append(line).append("\r\n");
line = bufferedReader.readLine();
}
bufferedReader.close();
String ecod = urlConnection.getContentEncoding();
if (ecod == null)
ecod = this.defaultContentEncoding;
httpResponser.setUrlString(urlString);
httpResponser.setDefaultPort(urlConnection.getURL()
.getDefaultPort());
httpResponser.setPort(urlConnection.getURL().getPort());
httpResponser.setProtocol(urlConnection.getURL().getProtocol());
httpResponser.setContent(new String(temp.toString().getBytes(),
ecod));
httpResponser.setContentEncoding(ecod);
httpResponser.setCode(urlConnection.getResponseCode());
httpResponser.setMessage(urlConnection.getResponseMessage());
httpResponser.setContentType(urlConnection.getContentType());
httpResponser.setConnectTimeout(urlConnection.getConnectTimeout());
httpResponser.setReadTimeout(urlConnection.getReadTimeout());
return httpResponser;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
}
public class HttpResponse {
String urlString;
int defaultPort;
int port;
String protocol;
String contentEncoding;
String content;
String contentType;
int code;
String message;
int connectTimeout;
int readTimeout;
Vector<String> contentCollection;
public String getUrlString() {
return urlString;
}
public void setUrlString(String urlString) {
this.urlString = urlString;
}
public int getDefaultPort() {
return defaultPort;
}
public void setDefaultPort(int defaultPort) {
this.defaultPort = defaultPort;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getProtocol() {
return protocol;
}
public void setProtocol(String protocol) {
this.protocol = protocol;
}
public String getContentEncoding() {
return contentEncoding;
}
public void setContentEncoding(String contentEncoding) {
this.contentEncoding = contentEncoding;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public int getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(int readTimeout) {
this.readTimeout = readTimeout;
}
public Vector<String> getContentCollection() {
return contentCollection;
}
public void setContentCollection(Vector<String> contentCollection) {
this.contentCollection = contentCollection;
}
}
}

View File

@ -0,0 +1,29 @@
package org.bench4q.master.communication.agent;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "parameter")
public class ParameterModel {
private String key;
private String value;
@XmlElement
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@XmlElement
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

View File

@ -0,0 +1,53 @@
package org.bench4q.master.communication.agent;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "runScenario")
public class RunScenarioModel {
private int poolSize;
private int totalCount;
private List<UsePluginModel> usePlugins;
private List<UserBehaviorModel> userBehaviors;
@XmlElement
public int getPoolSize() {
return poolSize;
}
public void setPoolSize(int poolSize) {
this.poolSize = poolSize;
}
@XmlElement
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
@XmlElementWrapper(name = "usePlugins")
@XmlElement(name = "usePlugin")
public List<UsePluginModel> getUsePlugins() {
return usePlugins;
}
public void setUsePlugins(List<UsePluginModel> usePlugins) {
this.usePlugins = usePlugins;
}
@XmlElementWrapper(name = "userBehaviors")
@XmlElement(name = "userBehavior")
public List<UserBehaviorModel> getUserBehaviors() {
return userBehaviors;
}
public void setUserBehaviors(List<UserBehaviorModel> userBehaviors) {
this.userBehaviors = userBehaviors;
}
}

View File

@ -0,0 +1,21 @@
package org.bench4q.master.communication.agent;
import java.util.UUID;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "runScenarioResult")
public class RunScenarioResultModel {
private UUID runId;
@XmlElement
public UUID getRunId() {
return runId;
}
public void setRunId(UUID runId) {
this.runId = runId;
}
}

View File

@ -0,0 +1,35 @@
package org.bench4q.master.communication.agent;
import java.util.List;
import java.util.UUID;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "serverStatus")
public class ServerStatusModel {
private List<UUID> runningTests;
private List<UUID> finishedTests;
@XmlElementWrapper(name = "runningTests")
@XmlElement(name = "runningTest")
public List<UUID> getRunningTests() {
return runningTests;
}
public void setRunningTests(List<UUID> runningTests) {
this.runningTests = runningTests;
}
@XmlElementWrapper(name = "finishedTests")
@XmlElement(name = "finishedTest")
public List<UUID> getFinishedTests() {
return finishedTests;
}
public void setFinishedTests(List<UUID> finishedTests) {
this.finishedTests = finishedTests;
}
}

View File

@ -0,0 +1,19 @@
package org.bench4q.master.communication.agent;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "stopTest")
public class StopTestModel {
private boolean success;
@XmlElement
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
}

View File

@ -0,0 +1,91 @@
package org.bench4q.master.communication.agent;
import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "testBriefStatus")
public class TestBriefStatusModel {
private Date startDate;
private long elapsedTime;
private int successCount;
private int failCount;
private int finishedCount;
private int totalCount;
private int scenarioBehaviorCount;
private double averageResponseTime;
@XmlElement
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@XmlElement
public long getElapsedTime() {
return elapsedTime;
}
public void setElapsedTime(long elapsedTime) {
this.elapsedTime = elapsedTime;
}
@XmlElement
public int getSuccessCount() {
return successCount;
}
public void setSuccessCount(int successCount) {
this.successCount = successCount;
}
@XmlElement
public int getFailCount() {
return failCount;
}
public void setFailCount(int failCount) {
this.failCount = failCount;
}
@XmlElement
public int getFinishedCount() {
return finishedCount;
}
public void setFinishedCount(int finishedCount) {
this.finishedCount = finishedCount;
}
@XmlElement
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
@XmlElement
public double getAverageResponseTime() {
return averageResponseTime;
}
public void setAverageResponseTime(double averageResponseTime) {
this.averageResponseTime = averageResponseTime;
}
@XmlElement
public int getScenarioBehaviorCount() {
return scenarioBehaviorCount;
}
public void setScenarioBehaviorCount(int scenarioBehaviorCount) {
this.scenarioBehaviorCount = scenarioBehaviorCount;
}
}

View File

@ -0,0 +1,80 @@
package org.bench4q.master.communication.agent;
import java.util.Date;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "testDetail")
public class TestDetailModel {
private String pluginId;
private String pluginName;
private String behaviorName;
private Date startDate;
private Date endDate;
private long responseTime;
private boolean success;
@XmlElement
public String getPluginId() {
return pluginId;
}
public void setPluginId(String pluginId) {
this.pluginId = pluginId;
}
@XmlElement
public String getPluginName() {
return pluginName;
}
public void setPluginName(String pluginName) {
this.pluginName = pluginName;
}
@XmlElement
public String getBehaviorName() {
return behaviorName;
}
public void setBehaviorName(String behaviorName) {
this.behaviorName = behaviorName;
}
@XmlElement
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@XmlElement
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@XmlElement
public long getResponseTime() {
return responseTime;
}
public void setResponseTime(long responseTime) {
this.responseTime = responseTime;
}
@XmlElement
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
}

View File

@ -0,0 +1,94 @@
package org.bench4q.master.communication.agent;
import java.util.Date;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "testDetailStatus")
public class TestDetailStatusModel {
private Date startDate;
private long elapsedTime;
private int successCount;
private int failCount;
private int finishedCount;
private int totalCount;
private double averageResponseTime;
private List<TestDetailModel> testDetailModels;
@XmlElement
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
@XmlElement
public long getElapsedTime() {
return elapsedTime;
}
public void setElapsedTime(long elapsedTime) {
this.elapsedTime = elapsedTime;
}
@XmlElement
public int getSuccessCount() {
return successCount;
}
public void setSuccessCount(int successCount) {
this.successCount = successCount;
}
@XmlElement
public int getFailCount() {
return failCount;
}
public void setFailCount(int failCount) {
this.failCount = failCount;
}
@XmlElement
public int getFinishedCount() {
return finishedCount;
}
public void setFinishedCount(int finishedCount) {
this.finishedCount = finishedCount;
}
@XmlElement
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
@XmlElement
public double getAverageResponseTime() {
return averageResponseTime;
}
public void setAverageResponseTime(double averageResponseTime) {
this.averageResponseTime = averageResponseTime;
}
@XmlElementWrapper(name = "testDetails")
@XmlElement(name = "testDetail")
public List<TestDetailModel> getTestDetailModels() {
return testDetailModels;
}
public void setTestDetailModels(List<TestDetailModel> testDetailModels) {
this.testDetailModels = testDetailModels;
}
}

View File

@ -0,0 +1,43 @@
package org.bench4q.master.communication.agent;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "usePlugin")
public class UsePluginModel {
private String id;
private String name;
private List<ParameterModel> parameters;
@XmlElement
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElementWrapper(name = "parameters")
@XmlElement(name = "parameter")
public List<ParameterModel> getParameters() {
return parameters;
}
public void setParameters(List<ParameterModel> parameters) {
this.parameters = parameters;
}
}

View File

@ -0,0 +1,42 @@
package org.bench4q.master.communication.agent;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "userBehavior")
public class UserBehaviorModel {
private String use;
private String name;
private List<ParameterModel> parameters;
@XmlElement
public String getUse() {
return use;
}
public void setUse(String use) {
this.use = use;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElementWrapper(name = "parameters")
@XmlElement(name = "parameter")
public List<ParameterModel> getParameters() {
return parameters;
}
public void setParameters(List<ParameterModel> parameters) {
this.parameters = parameters;
}
}

View File

@ -0,0 +1,170 @@
package org.bench4q.master.communication.monitor;
import java.util.Map;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* @author wxr
*
*/
@XmlRootElement(name = "LogicalDisk")
public class LogicalDiskModel {
private String[] instances;
private Map<String, Double> freeSpacePercent;
private Map<String, Double> freeMegabytes;
// 磁盘活动百分比
private Map<String, Double> diskTimePercent;
private Map<String, Double> diskReadTimePercent;
private Map<String, Double> diskWriteTimePercent;
// 磁盘平均活动时间
private Map<String, Double> averageDiskTransferTimeInSecond;
private Map<String, Double> averageDiskReadTimeInSecond;
private Map<String, Double> averageDiskWriteTimeInSecond;
// 磁盘平均处理的字节
private Map<String, Double> averageDiskBytesPerTransfer;// 可计算吞吐率
private Map<String, Double> averageDiskBytesPerRead;
private Map<String, Double> averageDiskBytesPerWrite;
// 空闲百分比
private Map<String, Double> idleTimePercent;
// 平均队列长度
private Map<String, Double> averageDiskQueueLength;
// 当前队列长度
private Map<String, Double> currentDiskQueueLength;
@XmlElement(name = "Instance")
public String[] getInstances() {
return instances;
}
public void setInstances(String[] instances) {
this.instances = instances;
}
@XmlElement(name = "FreeSpacePercent")
public Map<String, Double> getFreeSpacePercent() {
return freeSpacePercent;
}
public void setFreeSpacePercent(Map<String, Double> freeSpacePercent) {
this.freeSpacePercent = freeSpacePercent;
}
public Map<String, Double> getFreeMegabytes() {
return freeMegabytes;
}
public void setFreeMegabytes(Map<String, Double> freeMegabytes) {
this.freeMegabytes = freeMegabytes;
}
public Map<String, Double> getDiskTimePercent() {
return diskTimePercent;
}
public void setDiskTimePercent(Map<String, Double> diskTimePercent) {
this.diskTimePercent = diskTimePercent;
}
public Map<String, Double> getDiskReadTimePercent() {
return diskReadTimePercent;
}
public void setDiskReadTimePercent(Map<String, Double> diskReadTimePercent) {
this.diskReadTimePercent = diskReadTimePercent;
}
public Map<String, Double> getDiskWriteTimePercent() {
return diskWriteTimePercent;
}
public void setDiskWriteTimePercent(Map<String, Double> diskWriteTimePercent) {
this.diskWriteTimePercent = diskWriteTimePercent;
}
public Map<String, Double> getAverageDiskTransferTimeInSecond() {
return averageDiskTransferTimeInSecond;
}
public void setAverageDiskTransferTimeInSecond(
Map<String, Double> averageDiskTransferTimeInSecond) {
this.averageDiskTransferTimeInSecond = averageDiskTransferTimeInSecond;
}
public Map<String, Double> getAverageDiskReadTimeInSecond() {
return averageDiskReadTimeInSecond;
}
public void setAverageDiskReadTimeInSecond(
Map<String, Double> averageDiskReadTimeInSecond) {
this.averageDiskReadTimeInSecond = averageDiskReadTimeInSecond;
}
public Map<String, Double> getAverageDiskWriteTimeInSecond() {
return averageDiskWriteTimeInSecond;
}
public void setAverageDiskWriteTimeInSecond(
Map<String, Double> averageDiskWriteTimeInSecond) {
this.averageDiskWriteTimeInSecond = averageDiskWriteTimeInSecond;
}
public Map<String, Double> getAverageDiskBytesPerTransfer() {
return averageDiskBytesPerTransfer;
}
public void setAverageDiskBytesPerTransfer(
Map<String, Double> averageDiskBytesPerTransfer) {
this.averageDiskBytesPerTransfer = averageDiskBytesPerTransfer;
}
public Map<String, Double> getAverageDiskBytesPerRead() {
return averageDiskBytesPerRead;
}
public void setAverageDiskBytesPerRead(
Map<String, Double> averageDiskBytesPerRead) {
this.averageDiskBytesPerRead = averageDiskBytesPerRead;
}
public Map<String, Double> getAverageDiskBytesPerWrite() {
return averageDiskBytesPerWrite;
}
public void setAverageDiskBytesPerWrite(
Map<String, Double> averageDiskBytesPerWrite) {
this.averageDiskBytesPerWrite = averageDiskBytesPerWrite;
}
public Map<String, Double> getIdleTimePercent() {
return idleTimePercent;
}
public void setIdleTimePercent(Map<String, Double> idleTimePercent) {
this.idleTimePercent = idleTimePercent;
}
public Map<String, Double> getAverageDiskQueueLength() {
return averageDiskQueueLength;
}
public void setAverageDiskQueueLength(
Map<String, Double> averageDiskQueueLength) {
this.averageDiskQueueLength = averageDiskQueueLength;
}
public Map<String, Double> getCurrentDiskQueueLength() {
return currentDiskQueueLength;
}
public void setCurrentDiskQueueLength(
Map<String, Double> currentDiskQueueLength) {
this.currentDiskQueueLength = currentDiskQueueLength;
}
}

View File

@ -0,0 +1,155 @@
package org.bench4q.master.entity;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JTextArea;
//import maxq.HttpCapture;
//import maxq.Utils.UserException;
import org.bench4q.master.entity.httpcapture.HttpCapture;
import org.bench4q.master.entity.httpcapture.Utils.UserException;
import org.springframework.stereotype.Component;
@Component
public class ScriptCapturer {
private int portForRecord;
private String scriptPath;
private boolean isRecording;
private boolean isProxyServerRunning;
private String ipHttpCaptureServerAdress;
private HttpCapture httpCapture;
private static final String HTTPCATUREGENERATOR_STRING = "org.bench4q.master.entity.httpcapture.generator.Bench4qCodeGenerator";
// private final String TESTIPADRESS = "127.0.0.1";
public ScriptCapturer() {
}
public ScriptCapturer(int portForRecord, String scriptParentPath,
String userName) throws UnknownHostException {
this.setPortForRecord(portForRecord);
this.setScriptPath(scriptParentPath + userName);
this.setIpHttpCaptureServerAdress(this._getLocalHostIp());
}
public boolean isRecording() {
return isRecording;
}
public void setRecording(boolean isRecording) {
this.isRecording = isRecording;
}
public String getScriptPath() {
return scriptPath;
}
public void setScriptPath(String scriptPath) {
this.scriptPath = scriptPath;
}
public boolean isProxyServerRunning() {
return isProxyServerRunning;
}
public void setProxyServerRunning(boolean isProxyServerRunning) {
this.isProxyServerRunning = isProxyServerRunning;
}
public String getIpHttpCaptureServerAdress() {
return ipHttpCaptureServerAdress;
}
public void setIpHttpCaptureServerAdress(String ipHttpCaptureServerAdress) {
this.ipHttpCaptureServerAdress = ipHttpCaptureServerAdress;
}
public int getPortForRecord() {
return portForRecord;
}
public void setPortForRecord(int portForRecord) {
this.portForRecord = portForRecord;
}
private String _getLocalHostIp() throws UnknownHostException {
InetAddress addr = InetAddress.getLocalHost();
return addr.getHostAddress().toString();
}
private void startHttpCaptureProxyServer() {
try {
httpCapture = new HttpCapture(this.getScriptPath(),
this.getPortForRecord(), HTTPCATUREGENERATOR_STRING,
new JTextArea());
httpCapture.startProxyServer();
this.setProxyServerRunning(true);
System.out.println("INFO: Proxy Server Started at Port: "
+ this.getPortForRecord());
} catch (IOException e1) {
System.out.println("Error When build the proxy server!");
e1.printStackTrace();
} catch (UserException e1) {
System.out.println("Error When build the proxy server!");
e1.printStackTrace();
}
}
public void shutHttpCaptureProxyServer() {
try {
if (!isProxyServerRunning()) {
return;
}
if (this.isRecording()) {
httpCapture.stopRecording();
}
httpCapture.shutProxyServer();
this.setProxyServerRunning(false);
} catch (IOException e1) {
System.out.println("Error When shut the httpCapture proxy server!");
e1.printStackTrace();
} catch (UserException e1) {
System.out.println("Error When shut the httpCapture proxy server!");
e1.printStackTrace();
}
}
public void startCurrentRecord() {
try {
if (!this.isProxyServerRunning()) {
this.startHttpCaptureProxyServer();
}
httpCapture.startRecording();
this.setRecording(true);
} catch (IOException e1) {
System.out.println("Error When start recording!");
e1.printStackTrace();
} catch (UserException e1) {
System.out.println("Error When start recording!");
e1.printStackTrace();
}
}
public void stopCurrentRecord() {
try {
if (!this.isRecording()) {
return;
}
httpCapture.stopRecording();
this.setRecording(false);
} catch (IOException e1) {
System.out.println("Error When stop recording!");
e1.printStackTrace();
} catch (UserException e1) {
System.out.println("Error When stop recording!");
e1.printStackTrace();
}
}
public String getScriptContent() {
return this.httpCapture.getScriptContent();
}
}

View File

@ -0,0 +1,85 @@
package org.bench4q.master.entity.db;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = "agent")
@XmlRootElement(name = "agent")
public class Agent {
private int id;
protected String hostName;
protected int port;
protected int maxLoad;
protected int remainLoad;
protected int currentStatus;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "hostName", nullable = false)
@XmlElement
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
@Column(name = "port", nullable = false)
@XmlElement
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Column(name = "maxLoad", nullable = false)
@XmlElement
public int getMaxLoad() {
return maxLoad;
}
public void setMaxLoad(int maxLoad) {
this.maxLoad = maxLoad;
}
@Column(name = "remainLoad", nullable = false)
@XmlElement
public int getRemainLoad() {
return remainLoad;
}
public void setRemainLoad(int remainLoad) {
this.remainLoad = remainLoad;
}
@Column(name = "currentStatus", nullable = false)
@XmlElement
public int getCurrentStatus() {
return currentStatus;
}
public void setCurrentStatus(int currentStatus) {
this.currentStatus = currentStatus;
}
}

View File

@ -0,0 +1,48 @@
package org.bench4q.master.entity.db;
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 = "behavior")
public class Behavior {
private int id;
private Script script;
private String behaviorString;
@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 = "scriptId", nullable = false)
public Script getScript() {
return script;
}
public void setScript(Script script) {
this.script = script;
}
@Column(name = "behaviorString", nullable = false)
public String getBehaviorString() {
return behaviorString;
}
public void setBehaviorString(String behaviorString) {
this.behaviorString = behaviorString;
}
}

View File

@ -0,0 +1,60 @@
package org.bench4q.master.entity.db;
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 = "group")
public class Group {
private int id;
private Behavior behavior;
private PlanConfig loadProfile;
private String forceStop;
@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 = "behaviorId", nullable = false)
public Behavior getBehavior() {
return behavior;
}
public void setBehavior(Behavior behavior) {
this.behavior = behavior;
}
@Column(name = "forceStop", nullable = false)
public String getForceStop() {
return forceStop;
}
public void setForceStop(String forceStop) {
this.forceStop = forceStop;
}
@ManyToOne
@JoinColumn(name = "loadProfileId", nullable = false)
public PlanConfig getLoadProfile() {
return loadProfile;
}
public void setLoadProfile(PlanConfig loadProfile) {
this.loadProfile = loadProfile;
}
}

View File

@ -0,0 +1,69 @@
package org.bench4q.master.entity.db;
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 = "planConfig")
public class PlanConfig {
private int id;
private TestPlan testPlan;
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;
}
@ManyToOne
@JoinColumn(name = "testPlanId", nullable = false)
public TestPlan getTestPlan() {
return testPlan;
}
public void setTestPlan(TestPlan testPlan) {
this.testPlan = testPlan;
}
@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

@ -0,0 +1,46 @@
package org.bench4q.master.entity.db;
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 = "plugin")
public class Plugin {
private int id;
private String use;
private String name;
@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 = "[use]", nullable = false)
public String getUse() {
return use;
}
public void setUse(String use) {
this.use = use;
}
@Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,52 @@
package org.bench4q.master.entity.db;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@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)
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "port", nullable = false)
@XmlElement
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
@Column(name = "inUse", nullable = false)
@XmlElement
public boolean isInUse() {
return inUse;
}
public void setInUse(boolean inUse) {
this.inUse = inUse;
}
}

View File

@ -0,0 +1,191 @@
package org.bench4q.master.entity.db;
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 = "sample")
public class Sample {
private int id;
private String name;
private int pluginId;
private int behaviorId;
private String paramsPassword;
private String paramsParameters;
private String paramsRealm;
private String paramsProxyport;
private String paramsCookies;
private String paramsProxypassword;
private String paramsHostauth;
private String paramsCookiepolicy;
private String paramsUri;
private String paramsUsername;
private String paramsRedirect;
private String paramsLocaladdress;
private String paramsProxylogin;
@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 = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "pluginId", nullable = false)
public int getPluginId() {
return pluginId;
}
public void setPluginId(int pluginId) {
this.pluginId = pluginId;
}
@Column(name = "behaviorId", nullable = false)
public int getBehaviorId() {
return behaviorId;
}
public void setBehaviorId(int behaviorId) {
this.behaviorId = behaviorId;
}
/**
* For Parameters in sample
*/
@Column(name = "paramsPassword", nullable = false)
public String getParamsPassword() {
return paramsPassword;
}
public void setParamsPassword(String paramsPassword) {
this.paramsPassword = paramsPassword;
}
@Column(name = "paramsParameters", nullable = false)
public String getParamsParameters() {
return paramsParameters;
}
public void setParamsParameters(String paramsParameters) {
this.paramsParameters = paramsParameters;
}
@Column(name = "paramsRealm", nullable = false)
public String getParamsRealm() {
return paramsRealm;
}
public void setParamsRealm(String paramsRealm) {
this.paramsRealm = paramsRealm;
}
@Column(name = "paramsProxyport", nullable = false)
public String getParamsProxyport() {
return paramsProxyport;
}
public void setParamsProxyport(String paramsProxyport) {
this.paramsProxyport = paramsProxyport;
}
@Column(name = "paramsCookies", nullable = false)
public String getParamsCookies() {
return paramsCookies;
}
public void setParamsCookies(String paramsCookies) {
this.paramsCookies = paramsCookies;
}
@Column(name = "paramsProxypassword", nullable = false)
public String getParamsProxypassword() {
return paramsProxypassword;
}
public void setParamsProxypassword(String paramsProxypassword) {
this.paramsProxypassword = paramsProxypassword;
}
@Column(name = "paramsHostauth", nullable = false)
public String getParamsHostauth() {
return paramsHostauth;
}
public void setParamsHostauth(String paramsHostauth) {
this.paramsHostauth = paramsHostauth;
}
@Column(name = "paramsCookiepolicy", nullable = false)
public String getParamsCookiepolicy() {
return paramsCookiepolicy;
}
public void setParamsCookiepolicy(String paramsCookiepolicy) {
this.paramsCookiepolicy = paramsCookiepolicy;
}
@Column(name = "paramsUri", nullable = false)
public String getParamsUri() {
return paramsUri;
}
public void setParamsUri(String paramsUri) {
this.paramsUri = paramsUri;
}
@Column(name = "paramsUsername", nullable = false)
public String getParamsUsername() {
return paramsUsername;
}
public void setParamsUsername(String paramsUsername) {
this.paramsUsername = paramsUsername;
}
@Column(name = "paramsRedirect", nullable = false)
public String getParamsRedirect() {
return paramsRedirect;
}
public void setParamsRedirect(String paramsRedirect) {
this.paramsRedirect = paramsRedirect;
}
@Column(name = "paramsLocaladdress", nullable = false)
public String getParamsLocaladdress() {
return paramsLocaladdress;
}
public void setParamsLocaladdress(String paramsLocaladdress) {
this.paramsLocaladdress = paramsLocaladdress;
}
@Column(name = "paramsProxylogin", nullable = false)
public String getParamsProxylogin() {
return paramsProxylogin;
}
public void setParamsProxylogin(String paramsProxylogin) {
this.paramsProxylogin = paramsProxylogin;
}
}

View File

@ -0,0 +1,91 @@
package org.bench4q.master.entity.db;
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.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name = "Script")
@XmlRootElement
public class Script {
private int id;
private String name;
private String scriptContent;
private int behaviorCount;
private Date createDateTime;
private User user;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
@XmlElement
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "name", nullable = false)
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "createDateTime", nullable = false)
@XmlElement
public Date getCreateDateTime() {
return createDateTime;
}
public void setCreateDateTime(Date createDateTime) {
this.createDateTime = createDateTime;
}
@ManyToOne
@JoinColumn(name = "userId", nullable = false)
@XmlElement
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Column(name = "scriptContent", columnDefinition = "TEXT", nullable = false)
@XmlElement
public String getScriptContent() {
return scriptContent;
}
public void setScriptContent(String scriptContent) {
this.scriptContent = scriptContent;
}
@XmlElement
@Column(name = "behaviorCount", nullable = false)
public int getBehaviorCount() {
return behaviorCount;
}
public void setBehaviorCount(int behaviorCount) {
this.behaviorCount = behaviorCount;
}
}

View File

@ -0,0 +1,61 @@
package org.bench4q.master.entity.db;
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 = "testplan")
public class TestPlan {
private int id;
private String name;
private Date createDateTime;
private User user;
@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 = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "createDateTime", nullable = false)
public Date getCreateDateTime() {
return createDateTime;
}
public void setCreateDateTime(Date createDateTime) {
this.createDateTime = createDateTime;
}
@ManyToOne
@JoinColumn(name = "userId", nullable = false)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}

View File

@ -0,0 +1,60 @@
package org.bench4q.master.entity.db;
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.OneToOne;
import javax.persistence.Table;
@Entity
@Table(name = "TestPlanScript")
public class TestPlanScript {
private int id;
private Script script;
private int requireLoad;
private TestPlan testPlan;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@OneToOne
@JoinColumn(name = "scriptId", nullable = false)
public Script getScript() {
return script;
}
public void setScript(Script script) {
this.script = script;
}
@Column(name = "requireLoad", nullable = false)
public int getRequireLoad() {
return requireLoad;
}
public void setRequireLoad(int requireLoad) {
this.requireLoad = requireLoad;
}
@OneToOne
@JoinColumn(name = "testPlanId", nullable = false)
public TestPlan getTestPlan() {
return testPlan;
}
public void setTestPlan(TestPlan testPlan) {
this.testPlan = testPlan;
}
}

View File

@ -0,0 +1,60 @@
package org.bench4q.master.entity.db;
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 = "timer")
public class Timer {
private int id;
private Plugin plugin;
private Behavior behavior;
private String name;
@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 = "pluginId", nullable = false)
public Plugin getPlugin() {
return plugin;
}
public void setPlugin(Plugin plugin) {
this.plugin = plugin;
}
@ManyToOne
@JoinColumn(name = "behaviorId", nullable = false)
public Behavior getBehavior() {
return behavior;
}
public void setBehavior(Behavior behavior) {
this.behavior = behavior;
}
@Column(name = "name", nullable = false)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -0,0 +1,56 @@
package org.bench4q.master.entity.db;
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;
@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;
}
}

View File

@ -0,0 +1,209 @@
package org.bench4q.master.entity.httpcapture;
import java.util.Vector;
public class Action {
private static String LINE_SEP = System.getProperty("line.separator");
private String url;
private String method;
private String expected_result;
private int delayTime;
private int expected_size;
private int timeout;
private Vector<HeaderValue> headers;
private Vector<Param> queryStringParams;
private Vector<Param> bodyParams;
private String multiPartData;
public Action()
{
this.headers = new Vector<HeaderValue>();
this.queryStringParams = new Vector<Param>();
this.bodyParams = new Vector<Param>();
this.expected_result = "";
this.multiPartData = "";
}
public void setUrl(String url)
{
this.url = url;
}
public String getUrl()
{
return this.url;
}
public void setMethod(String method)
{
this.method = method;
}
public String getMethod()
{
return this.method;
}
public void setExpectedResult(String str)
{
this.expected_result = str;
}
public String getExpectedResult()
{
return this.expected_result;
}
public void setDelayTime(int seconds)
{
this.delayTime = seconds;
}
public int getDelayTime()
{
return this.delayTime;
}
public void setExpectedSize(int bytes)
{
this.expected_size = bytes;
}
public int getExpectedSize()
{
return this.expected_size;
}
public void setTimeout(int seconds)
{
this.timeout = seconds;
}
public int getTimeout()
{
return this.timeout;
}
public int getHeaderCount()
{
return this.headers.size();
}
public HeaderValue[] getHeaders()
{
HeaderValue[] list = new HeaderValue[this.headers.size()];
this.headers.copyInto(list);
return list;
}
public void addHeader(HeaderValue p)
{
this.headers.addElement(p);
}
public void removeHeader(HeaderValue p)
{
this.headers.removeElement(p);
}
public int getParamsCount()
{
return getParams().length;
}
public int getQueryStringParamCount()
{
return this.queryStringParams.size();
}
public int getBodyParamCount()
{
return this.bodyParams.size();
}
public Param[] getQueryStringParams()
{
Param[] list = new Param[this.queryStringParams.size()];
this.queryStringParams.copyInto(list);
return list;
}
public Param[] getBodyParams()
{
Param[] list = new Param[this.bodyParams.size()];
this.bodyParams.copyInto(list);
return list;
}
public Param[] getParams()
{
@SuppressWarnings("unchecked")
Vector<Param> v = (Vector<Param>)this.queryStringParams.clone();
v.addAll(this.bodyParams);
Param[] list = new Param[v.size()];
v.copyInto(list);
return list;
}
public void addQueryStringParam(Param p)
{
this.queryStringParams.addElement(p);
}
public void addBodyParam(Param p)
{
this.bodyParams.addElement(p);
}
public void removeQueryStringParam(Param p)
{
this.queryStringParams.removeElement(p);
}
public void removeBodyParam(Param p)
{
this.bodyParams.removeElement(p);
}
public String toXML()
{
StringBuffer str = new StringBuffer(1024);
str.append(" ");
str.append("<action url=\"").append(this.url).append("\" ");
str.append(LINE_SEP).append(" ");
str.append("method=\"").append(this.method).append("\" ");
str.append(LINE_SEP).append(" ");
str.append("delayTime=\"").append(this.delayTime).append("\" ");
str.append(LINE_SEP).append(" ");
str.append("expected-result=\"").append(this.expected_result).append("\"");
str.append(LINE_SEP).append(" ");
str.append("expected-result-size=\"").append(this.expected_size).append("\"");
str.append(LINE_SEP).append(" ");
str.append("timeout=\"").append(this.timeout).append("\">");
Param[] params = getQueryStringParams();
for (int i = 0; i < params.length; ++i) {
str.append(LINE_SEP).append(" ");
str.append("<param name=\"").append(params[i].name);
str.append("\" value=\"").append(params[i].value).append("\"/>");
}
params = getBodyParams();
for (int i = 0; i < params.length; ++i) {
str.append(LINE_SEP).append(" ");
str.append("<param name=\"").append(params[i].name);
str.append("\" value=\"").append(params[i].value).append("\"/>");
}
str.append(LINE_SEP);
str.append(" </action>");
return str.toString();
}
public void setMultiPartData(String multiPartData)
{
this.multiPartData = multiPartData;
}
public String getMultiPartData()
{
return this.multiPartData;
}
}

View File

@ -0,0 +1,76 @@
package org.bench4q.master.entity.httpcapture;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.bench4q.master.communication.agent.RunScenarioModel;
import org.bench4q.master.communication.agent.UsePluginModel;
import org.bench4q.master.communication.agent.UserBehaviorModel;
public class Bench4qTestScriptAdapter implements IScriptAdapter {
private RunScenarioModel runScenarioModel;
public RunScenarioModel getRunScenarioModel() {
return runScenarioModel;
}
private void setRunScenarioModel(RunScenarioModel runScenarioModel) {
this.runScenarioModel = runScenarioModel;
}
public Bench4qTestScriptAdapter(RunScenarioModel runScenarioModel) {
this.runScenarioModel = runScenarioModel;
}
public void appendUsePluginsToScenario(List<UsePluginModel> usePluginModels) {
this.runScenarioModel.setUsePlugins(usePluginModels);
}
public void insertUserBehaviorsToScenario(UserBehaviorModel userModel) {
List<UserBehaviorModel> userBehaviors = this.runScenarioModel
.getUserBehaviors();
if (userBehaviors == null) {
userBehaviors = new ArrayList<UserBehaviorModel>();
}
userBehaviors.add(userModel);
this.runScenarioModel.setUserBehaviors(userBehaviors);
}
public String getText() {
StringWriter stringWriter = new StringWriter();
try {
Marshaller marshaller = JAXBContext.newInstance(
this.runScenarioModel.getClass()).createMarshaller();
marshaller.marshal(this.runScenarioModel, stringWriter);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
} catch (JAXBException e) {
e.printStackTrace();
}
return stringWriter.toString();
}
public void setText(String text) {
if (text.isEmpty()) {
this.setRunScenarioModel(new RunScenarioModel());
return;
}
try {
Unmarshaller unmarshaller = JAXBContext.newInstance(
this.runScenarioModel.getClass()).createUnmarshaller();
this.runScenarioModel = (RunScenarioModel) unmarshaller
.unmarshal(new ByteArrayInputStream(text.getBytes()));
} catch (JAXBException e) {
e.printStackTrace();
}
}
}

View File

@ -0,0 +1,270 @@
package org.bench4q.master.entity.httpcapture;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.python.util.PythonInterpreter;
public class Config {
private static Config config = null;
private static final Log log = LogFactory.getLog(Config.class);
private static Properties props;
private String pythonPath;
private int port = 8090;
private boolean debug;
private boolean quiet;
private String exist;
private String replace;
private List<String> includeList;
private List<String> excludeList;
private List<Pattern> includePatterns = new ArrayList<Pattern>();
private List<Pattern> excludePatterns = new ArrayList<Pattern>();
private String scriptArg;
private ProxySettings proxySettings;
private static String defDriverPkgName = "com.bitmechanic.maxq";
private static String defValidatorPkgName = "com.bitmechanic.maxq";
static {
Layout layout = new PatternLayout("%d [%t] %-5p %c - %m%n");
Logger.getRootLogger().addAppender(
new ConsoleAppender(layout, "System.err"));
}
public static Config getConfig() {
if (config == null)
initConfig();
return config;
}
public static void initConfig() {
config = new Config();
String maxqDir = System.getProperty("maxq.dir");
String pathSep = System.getProperty("file.separator");
String propertiesFileName = System.getProperty("user.dir")
+ "\\src\\main\\resources\\org\\bench4q\\master\\config\\httpCaptureConfig\\maxq.properties";
InputStream propertiesStream = Config.class.getClassLoader()
.getResourceAsStream(propertiesFileName);
props = new Properties();
if (propertiesStream != null) {
try {
props.load(propertiesStream);
log.debug("Generator: "
+ props.getProperty("generator.classnames"));
} catch (IOException e) {
throw new ExceptionInInitializerError(e);
}
}
config.addPythonPath(maxqDir + pathSep + "jython");
String path = config.getProperty("python.path");
if (path != null) {
config.addPythonPath(path);
}
String portStr = props.getProperty("local.proxy.port");
if (portStr != null)
config.port = Integer.parseInt(portStr);
}
public void completeInit() throws Utils.UserException {
Level level = this.quiet ? Level.WARN : this.debug ? Level.ALL
: Level.INFO;
Logger.getRootLogger().setLevel(level);
System.setProperty("org.apache.commons.logging.simplelog.defaultlog",
"warn");
Properties ppref = new Properties();
if (getPythonPath() != null)
ppref.put("python.path", getPythonPath());
PythonInterpreter.initialize(System.getProperties(), ppref,
new String[0]);
String host = getProperty("remote.proxy.host");
Integer port = getPropertyInt("remote.proxy.port");
if ((host == null ? 1 : 0) != (port == null ? 1 : 0))
throw new Utils.UserException(
"Not using proxy server. You must set both remote.proxy.host and remote.proxy.port.");
if ((host != null) && (port != null)) {
this.proxySettings = new ProxySettings();
this.proxySettings.host = host;
this.proxySettings.port = port.intValue();
log.info("Proxying requests via " + this.proxySettings.host + ":"
+ Integer.toString(this.proxySettings.port));
}
}
public String getProperty(String prop) {
return (String) props.get(prop);
}
public String getProperty(String prop, String def) {
String val = getProperty(prop);
return (val == null) || (val.equals("")) ? def : val;
}
public void setProperty(String property, String value) {
props.setProperty(property, value);
}
public Integer getPropertyInt(String prop) throws Utils.UserException {
String s = getProperty(prop);
if (s == null)
return null;
try {
return new Integer(s);
} catch (NumberFormatException e) {
}
throw new Utils.UserException(prop + " property must be an integer");
}
public void addPythonPath(String path) {
if (this.pythonPath == null)
this.pythonPath = path;
else
this.pythonPath = (this.pythonPath
+ System.getProperty("path.separator") + path);
}
public String getPythonPath() {
return this.pythonPath;
}
public void setPort(int pt) {
this.port = pt;
}
public int getPort() {
return this.port;
}
public void setDebug(boolean d) {
this.debug = d;
}
public boolean isDebug() {
return this.debug;
}
public void setQuiet(boolean q) {
this.quiet = q;
}
public boolean isQuiet() {
return this.quiet;
}
public void setExist(String e) {
this.exist = e;
}
public String getExist() {
return this.exist;
}
public void setReplace(String e) {
this.replace = e;
}
public String getReplace() {
return this.replace;
}
public void setIncludePatterns(String[] pats) {
this.includeList = Arrays.asList(pats);
createPatterns(this.includeList, this.includePatterns);
}
public void setExcludePatterns(String[] pats) {
this.excludeList = Arrays.asList(pats);
createPatterns(this.excludeList, this.excludePatterns);
}
public List<Pattern> getIncludePatterns() {
return this.includePatterns;
}
public List<Pattern> getExcludePatterns() {
return this.excludePatterns;
}
public void setScriptArg(String arg) {
this.scriptArg = arg;
}
public String getScriptArg() {
return this.scriptArg;
}
public static String getDriverPkgName() {
return System.getProperty("maxq.driverpkgname", defDriverPkgName);
}
public static String getValidatorPkgName() {
return System.getProperty("maxq.validatorpkgname", defValidatorPkgName);
}
public static Log getTestLogger() {
return LogFactory.getLog("com.bitmechanic.maxq.testrun");
}
public ProxySettings getProxySettings() {
return this.proxySettings;
}
public void setProxySettings(ProxySettings proxySettings) {
this.proxySettings = proxySettings;
}
private void createPatterns(List<String> list,
List<Pattern> excludePatterns2) {
Iterator<String> iter = list.iterator();
excludePatterns2.clear();
while (iter.hasNext())
try {
Pattern p = Pattern.compile(iter.next().toString());
excludePatterns2.add(p);
} catch (PatternSyntaxException e) {
log.error(e);
}
}
public static class ProxySettings {
String host;
int port;
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
}
}

View File

@ -0,0 +1,78 @@
package org.bench4q.master.entity.httpcapture;
public class HeaderValue {
public static final String GENERAL_CACHE_CONTROL = "Cache-Control";
public static final String GENERAL_CONNECTION = "Connection";
public static final String GENERAL_DATE = "Date";
public static final String GENERAL_PRAGMA = "Pragma";
public static final String GENERAL_TRAILER = "Trailer";
public static final String GENERAL_TRANSFER_ENC = "Transfer-Encoding";
public static final String GENERAL_UPGRADE = "Upgrade";
public static final String GENERAL_VIA = "Via";
public static final String GENERAL_WARNING = "Warning";
public static final String REQUEST_ACCEPT = "Accept";
public static final String REQUEST_ACCEPT_CHARSET = "Accept-Charset";
public static final String REQUEST_ACCEPT_ENCODING = "Accept-Encoding";
public static final String REQUEST_ACCEPT_LANGUAGE = "Accept-Language";
public static final String REQUEST_AUTHORIZATION = "Authorization";
public static final String REQUEST_EXPECT = "Expect";
public static final String REQUEST_FROM = "From";
public static final String REQUEST_HOST = "Host";
public static final String REQUEST_IF_MATCH = "If-Match";
public static final String REQUEST_IF_MODIFIED_SINCE = "If-Modified-Since";
public static final String REQUEST_IF_NONE_MATCH = "If-None-Match";
public static final String REQUEST_IF_RANGE = "If-Range";
public static final String REQUEST_IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
public static final String REQUEST_MAX_FORWARDS = "Max-Forwards";
public static final String REQUEST_PROXY_AUTHORIZATION = "Proxy-Authorization";
public static final String REQUEST_RANGE = "Range";
public static final String REQUEST_REFERER = "Referer";
public static final String REQUEST_TE = "TE";
public static final String REQUEST_USER_AGENT = "User-Agent";
public static final String RESPONSE_AGE = "Age";
public static final String RESPONSE_ETAG = "ETag";
public static final String RESPONSE_LOCATION = "Location";
public static final String RESPONSE_PROXY_AUTHENTICATE = "Proxy-Authenticate";
public static final String RESPONSE_RETRY_AFTER = "Retry-After";
public static final String RESPONSE_SERVER = "Server";
public static final String RESPONSE_VARY = "Vary";
public static final String RESPONSE_WWW_AUTHENTICATE = "WWW-Authenticate";
public static final String ENTITY_ALLOW = "Allow";
public static final String ENTITY_CONTENT_ENCODING = "Content-Encoding";
public static final String ENTITY_CONTENT_LANGUAGE = "Content-Language";
public static final String ENTITY_CONTENT_LENGHT = "Content-Length";
public static final String ENTITY_CONTENT_LOCATION = "Content-Location";
public static final String ENTITY_CONTENT_MD5 = "Content-MD5";
public static final String ENTITY_CONTENT_RANGE = "Content-Range";
public static final String ENTITY_CONTENT_TYPE = "Content-Type";
public static final String ENTITY_EXPIRES = "Expires";
public static final String ENTITY_LAST_MODIFIED = "Last-Modified";
private String header;
private String value;
public HeaderValue(String header, String value)
{
this.header = header;
this.value = value;
}
public String getHeader()
{
return this.header;
}
public void setHeader(String header)
{
this.header = header;
}
public String getValue()
{
return this.value;
}
public void setValue(String value)
{
this.value = value;
}
}

View File

@ -0,0 +1,79 @@
package org.bench4q.master.entity.httpcapture;
import java.io.File;
import java.io.IOException;
import javax.swing.JTextArea;
import org.bench4q.master.communication.agent.RunScenarioModel;
public class HttpCapture {
private int localport;
private Config config;
private Test currentTest;
private ProxyServer proxy;
private File resultFile;
public HttpCapture(String filepath, int localport, String generator,
JTextArea textArea) {
this.localport = localport;
System.out.println(filepath + "\\Script.xml");
File file = new File(filepath);
if (!file.exists()) {
file.mkdirs();
}
this.resultFile = new File(filepath + "\\Script.xml");
this.config = Config.getConfig();
try {
this.config.completeInit();
this.proxy = new ProxyServer(this.localport);
} catch (Exception e) {
e.printStackTrace();
}
this.currentTest = new Test(this.proxy, new Bench4qTestScriptAdapter(
new RunScenarioModel()), generator);
}
public void startProxyServer() throws IOException, Utils.UserException {
this.proxy.start();
}
public void startRecording() throws IOException, Utils.UserException {
this.currentTest.startRecording();
this.resultFile.createNewFile();
this.currentTest.setTestFile(this.resultFile);
}
public void stopRecording() throws IOException, Utils.UserException {
this.currentTest.stopRecording();
this.currentTest.save();
}
public void shutProxyServer() throws IOException, Utils.UserException {
if (this.proxy.getServerSocket() != null) {
this.proxy.getServerSocket().close();
this.proxy.interrupt();
}
this.currentTest.close();
}
public String getScriptContent() {
return this.currentTest.getScriptContent();
}
public static void main(String[] args) {
try {
HttpCapture m = new HttpCapture("E:\\Temp", 8090,
"maxq.generator.IsacCodeGenerator", new JTextArea());
m.startProxyServer();
m.startRecording();
m.stopRecording();
m.startRecording();
m.stopRecording();
m.shutProxyServer();
} catch (Exception localException) {
}
}
}

View File

@ -0,0 +1,193 @@
package org.bench4q.master.entity.httpcapture;
import java.io.IOException;
import java.io.InputStream;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class HttpRequestHeader {
private static final Log log = LogFactory.getLog(HttpRequestHeader.class);
public String method = new String();
public String url = new String();
public String version = new String();
public String userAgent = new String();
public String referer = new String();
public String ifModifiedSince = new String();
public String accept = new String();
public String authorization = new String();
public String contentType = new String();
public int contentLength = -1;
public int oldContentLength = -1;
public String unrecognized = new String();
public boolean pragmaNoCache = false;
static final String CR = "\r\n";
private InputStream input;
public HttpRequestHeader(InputStream in)
throws IOException
{
this.input = in;
StringTokenizer tz = new StringTokenizer(readLine());
this.method = getToken(tz).toUpperCase();
this.url = getToken(tz);
this.version = getToken(tz);
while (true)
{
String line = readLine();
log.trace(line);
tz = new StringTokenizer(line);
String Token = getToken(tz);
if (Token.length() == 0) {
break;
}
if (Token.equalsIgnoreCase("USER-AGENT:"))
{
this.userAgent = getRemainder(tz);
} else if (Token.equalsIgnoreCase("ACCEPT:"))
{
this.accept = (this.accept + " " + getRemainder(tz));
}
else if (Token.equalsIgnoreCase("REFERER:"))
{
this.referer = getRemainder(tz);
}
else if (Token.equalsIgnoreCase("PRAGMA:"))
{
Token = getToken(tz);
if (Token.equalsIgnoreCase("NO-CACHE"))
this.pragmaNoCache = true;
else
this.unrecognized =
(this.unrecognized + "Pragma:" + Token + " " +
getRemainder(tz) + "\n");
} else if (Token.equalsIgnoreCase("AUTHORIZATION:"))
{
this.authorization = getRemainder(tz);
}
else if (Token.equalsIgnoreCase("IF-MODIFIED-SINCE:"))
{
String str = getRemainder(tz);
int index = str.indexOf(";");
if (index == -1) {
this.ifModifiedSince = str;
} else {
this.ifModifiedSince = str.substring(0, index);
index = str.indexOf("=");
if (index != -1) {
str = str.substring(index + 1);
this.oldContentLength = Integer.parseInt(str);
}
}
} else if (Token.equalsIgnoreCase("CONTENT-LENGTH:")) {
Token = getToken(tz);
this.contentLength = Integer.parseInt(Token);
} else if (Token.equalsIgnoreCase("CONTENT-TYPE:")) {
this.contentType = getRemainder(tz);
} else {
this.unrecognized = (this.unrecognized + Token + " " + getRemainder(tz) + "\r\n");
}
}
}
String readLine()
throws IOException
{
StringBuffer sb = new StringBuffer();
int c;
while ((c = this.input.read()) != 10)
{
if (c == -1)
throw new IOException("unterminated line in request header");
sb.append((char)c);
}
return sb.toString();
}
public String toString(boolean sendUnknowen)
{
if (this.method.length() == 0) {
this.method = "GET";
}
String Request = this.method + " " + this.url + " HTTP/1.0" + "\r\n";
if (this.userAgent.length() > 0) {
Request = Request + "User-Agent:" + this.userAgent + "\r\n";
}
if (this.referer.length() > 0) {
Request = Request + "Referer:" + this.referer + "\r\n";
}
if (this.pragmaNoCache) {
Request = Request + "Pragma: no-cache\r\n";
}
if (this.ifModifiedSince.length() > 0) {
Request = Request + "If-Modified-Since: " + this.ifModifiedSince + "\r\n";
}
if (this.accept.length() > 0)
Request = Request + "Accept: " + this.accept + "\r\n";
else {
Request = Request + "Accept: */* \r\n";
}
if (this.contentType.length() > 0) {
Request = Request + "Content-Type: " + this.contentType + "\r\n";
}
if (this.contentLength > 0) {
Request = Request + "Content-Length: " + this.contentLength + "\r\n";
}
if (this.authorization.length() != 0) {
Request = Request + "Authorization: " + this.authorization + "\r\n";
}
if ((sendUnknowen) &&
(this.unrecognized.length() != 0)) {
Request = Request + this.unrecognized;
}
Request = Request + "\r\n";
return Request;
}
public String toString()
{
return toString(true);
}
String getToken(StringTokenizer tk)
{
String str = "";
if (tk.hasMoreTokens())
str = tk.nextToken();
return str;
}
String getRemainder(StringTokenizer tk)
{
String str = "";
if (tk.hasMoreTokens())
str = tk.nextToken();
while (tk.hasMoreTokens()) {
str = str + " " + tk.nextToken();
}
return str;
}
}

View File

@ -0,0 +1,241 @@
package org.bench4q.master.entity.httpcapture;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JOptionPane;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.python.core.PyDictionary;
import org.python.core.PyString;
import org.python.core.PyTuple;
public class HttpTestCase {
private Config config = Config.getConfig();
protected HttpMethod method = null;
protected HttpClient client = new HttpClient();
protected String data;
private boolean followRedirects = false;
private String charset;
public void setCharset(String cs) {
this.charset = cs;
}
public HttpTestCase(String name) {
Config.ProxySettings proxy = this.config.getProxySettings();
if (proxy != null) {
HostConfiguration hc = this.client.getHostConfiguration();
hc.setProxy(proxy.host, proxy.port);
}
}
public void Run() throws Throwable {
}
public HttpMethod getMethod() {
return this.method;
}
private void cleanupMethod() {
if (this.method != null) {
this.method.releaseConnection();
this.method = null;
}
}
public void get(String url) throws IOException {
get(url, null);
}
public void get(String url, Object[] args) throws IOException {
cleanupMethod();
this.method = new GetMethod(url);
if (args != null) {
this.method.setQueryString(paramsToNV(args));
}
this.method.setFollowRedirects(this.followRedirects);
this.client.executeMethod(this.method);
}
public void post(String url) throws IOException {
post(url, null);
}
public void post(String url, Object[] args) throws IOException {
cleanupMethod();
PostMethod post = new PostMethod(url);
if (this.charset != null) {
post.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded; charset="
+ this.charset);
}
if (args != null) {
post.setRequestBody(paramsToNV(args));
}
this.method = post;
this.method.setFollowRedirects(this.followRedirects);
this.client.executeMethod(this.method);
}
public void postMultiPart(String url, String data, int contLen)
throws IOException {
postMultiPart(url, data, contLen, null);
}
public void postMultiPart(String url, String data, int contLen,
Object[] args) throws IOException {
cleanupMethod();
PostMethod multipartPostMethod = new PostMethod(url);
multipartPostMethod.addParameter("data", data);
if (args != null) {
multipartPostMethod.setQueryString(paramsToNV(args));
}
this.method = multipartPostMethod;
this.method.setFollowRedirects(this.followRedirects);
this.client.executeMethod(this.method);
}
public NameValuePair[] paramsToNV(Object[] params) {
NameValuePair[] res = new NameValuePair[params.length];
for (int i = 0; i < params.length; ++i) {
Object param = params[i];
if (param instanceof PyTuple) {
PyTuple pyParam = (PyTuple) param;
res[i] = new NameValuePair(pyParam.__getitem__(0).toString(),
pyParam.__getitem__(1).toString());
} else if (param instanceof NameValuePair) {
res[i] = ((NameValuePair) param);
}
}
return res;
}
public String urlDecode(String s) {
return staticUrlDecode(s);
}
public static String staticUrlDecode(String s) {
String sUrl = "";
ByteArrayOutputStream out = new ByteArrayOutputStream(s.length());
for (int count = 0; count < s.length(); ++count)
if (s.charAt(count) == '%') {
++count;
if (count < s.length()) {
int a = Character.digit(s.charAt(count++), 16);
a <<= 4;
int b = Character.digit(s.charAt(count), 16);
if ((a + b == 39) || (a + b == 132))
out.write(92);
out.write(a + b);
} else {
out.write(37);
}
} else if (s.charAt(count) == '+') {
out.write(32);
} else {
sUrl += s.charAt(count);
out.write(s.charAt(count));
}
System.out.println(sUrl);
return out.toString();
}
protected void responseOK() throws URIException {
}
protected boolean responseContainsURI(String uri) throws URIException {
return ((this.method != null) && (this.method.getURI().getPath()
.indexOf(uri) != -1));
}
protected boolean responseContains(String text) {
try {
if ((this.method == null)
|| (this.method.getResponseBody() == null))
return false;
this.data = this.method.getResponseBodyAsString();
} catch (IOException e) {
e.printStackTrace();
}
return (this.data.indexOf(text) != -1);
}
protected void printResponse() {
try {
System.err.println(new String(this.method.getResponseBody()));
} catch (IOException e) {
e.printStackTrace();
}
}
public String getResponse() throws IOException {
return this.method.getResponseBodyAsString();
}
public byte[] getResponseAsBytes() throws IOException {
return this.method.getResponseBody();
}
public int getResponseCode() {
return getMethod().getStatusCode();
}
public PyDictionary getResponseHeader() {
PyDictionary dict = new PyDictionary();
Header[] headers = this.method.getResponseHeaders();
for (int i = 0; i < headers.length; ++i)
dict.__setitem__(new PyString(headers[i].getName()), new PyString(
headers[i].getValue()));
return dict;
}
public String getScriptArg() {
return this.config.getScriptArg();
}
public boolean userConfirm(String msg) {
int rc = JOptionPane.showConfirmDialog(null, msg, "HttpCapture", 2);
return (rc == 0);
}
public String userInput(String msg) {
return JOptionPane.showInputDialog(null, msg, "HttpCapture", 3);
}
public String getStrutsToken() throws IOException {
String responseString = new String(
this.method.getResponseBodyAsString());
String strutsToken = null;
int tokenIDIndex = responseString.toLowerCase().indexOf(
"org.apache.struts.taglib.html.TOKEN".toLowerCase());
int nextValue = responseString.toLowerCase().indexOf(
"value=\"".toLowerCase(), tokenIDIndex);
strutsToken = responseString.substring(nextValue + "value=\"".length(),
nextValue + "value=\"".length() + 32);
return strutsToken;
}
}

View File

@ -0,0 +1,23 @@
package org.bench4q.master.entity.httpcapture;
import java.util.List;
import org.bench4q.master.communication.agent.RunScenarioModel;
import org.bench4q.master.communication.agent.UsePluginModel;
import org.bench4q.master.communication.agent.UserBehaviorModel;
public interface IScriptAdapter {
public abstract RunScenarioModel getRunScenarioModel();
public abstract void appendUsePluginsToScenario(
List<UsePluginModel> usePluginModels);
public abstract void insertUserBehaviorsToScenario(
UserBehaviorModel userModel);
public abstract String getText();
public abstract void setText(String paramString);
}

View File

@ -0,0 +1,6 @@
package org.bench4q.master.entity.httpcapture;
public class Param {
public String name;
public String value;
}

View File

@ -0,0 +1,90 @@
package org.bench4q.master.entity.httpcapture;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class ProxyServer extends Thread {
private Vector<Observer> listeners;
private ServerSocket srvSock;
private int count;
private static final Log log = LogFactory.getLog(ProxyServer.class);
public ProxyServer() throws IOException
{
this(0);
}
public ProxyServer(int port)
throws IOException
{
this.srvSock = new ServerSocket(port);
this.listeners = new Vector<Observer>();
}
public void addObserver(Observer proxy)
{
this.listeners.addElement(proxy);
}
public void removeObserver(Observer proxy)
{
this.listeners.removeElement(proxy);
}
public void processRequest(HttpRequestHeader header, byte[] requestBody) throws Exception
{
for (Enumeration<Observer> e = this.listeners.elements(); e.hasMoreElements(); ) {
Observer pl = (Observer)e.nextElement();
pl.processRequest(header, requestBody);
}
}
public void processResponse(HttpRequestHeader header, byte[] response) throws Exception
{
for (Enumeration<Observer> e = this.listeners.elements(); e.hasMoreElements(); ) {
Observer pl = (Observer)e.nextElement();
pl.processResponse(header, response);
}
}
public void run()
{
System.out.println(" in run");
while (!Thread.interrupted())
if (!this.srvSock.isClosed())
try {
Socket s = this.srvSock.accept();
RequestHandler handler = new RequestHandler(this, s);
log.trace("New connection. Creating new RequestHandler thread.");
Thread t = new Thread(handler, "MaxQRequestHandler #" + this.count);
t.start();
this.count += 1;
}
catch (Throwable localThrowable)
{
}
}
int getLocalPort()
{
return this.srvSock.getLocalPort();
}
public ServerSocket getServerSocket() {
return this.srvSock;
}
public static abstract interface Observer
{
public abstract void processRequest(HttpRequestHeader paramHttpRequestHeader, byte[] paramArrayOfByte)
throws Exception;
public abstract void processResponse(HttpRequestHeader paramHttpRequestHeader, byte[] paramArrayOfByte)
throws Exception;
}
}

View File

@ -0,0 +1,197 @@
package org.bench4q.master.entity.httpcapture;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class RequestHandler implements Runnable {
private static final Log log = LogFactory.getLog(RequestHandler.class);
private Config config = Config.getConfig();
private InputStream clientIn;
private InputStream serverIn;
private OutputStream clientOut;
private OutputStream serverOut;
private HttpRequestHeader header;
private ProxyServer proxyServer;
private Socket clientSocket;
private Socket serverSocket;
private ByteArrayOutputStream buffer;
private static Object mutex = new Object();
RequestHandler(ProxyServer proxyServer, Socket s) {
assert (s != null);
this.clientSocket = s;
this.buffer = new ByteArrayOutputStream();
this.proxyServer = proxyServer;
}
private void initClientServerConnections(Socket s) throws Throwable {
this.clientIn = new BufferedInputStream(s.getInputStream());
this.clientOut = s.getOutputStream();
try {
this.header = new HttpRequestHeader(this.clientIn);
} catch (IOException e) {
log.info("truncated request from browser: " + e.getMessage()
+ this.header.url);
throw new Utils.SilentException();
}
if (!this.header.url.startsWith("http"))
throw new Utils.UserException(
"MaxQ only supports the HTTP protocol.");
URL url = new URL(this.header.url);
Config.ProxySettings proxy = this.config.getProxySettings();
int port;
String host;
if (proxy != null) {
host = proxy.host;
port = proxy.port;
} else {
host = url.getHost();
port = url.getPort();
}
if (port < 1)
port = 80;
try {
this.serverSocket = new Socket(InetAddress.getByName(host), port);
} catch (ConnectException e) {
String msg = "Cannot connect to ";
if (proxy != null)
msg = msg + "proxy server ";
msg = msg + host;
if (port != 80)
msg = msg + " on port " + Integer.toString(port);
throw new Utils.UserException(msg + ".");
}
try {
this.serverIn = this.serverSocket.getInputStream();
this.serverOut = this.serverSocket.getOutputStream();
} catch (Throwable e) {
this.serverSocket.close();
this.serverSocket = null;
throw e;
}
}
private String stripProxyInfoFromRequestHeader()
throws MalformedURLException {
String res = "";
String origUrl = this.header.url;
URL url = new URL(origUrl);
this.header.url = url.getFile();
res = this.header.toString();
this.header.url = origUrl;
return res;
}
public void run() {
try {
try {
int rs = this.clientSocket.getReceiveBufferSize();
int ss = this.clientSocket.getSendBufferSize();
int BUF_SIZE = rs < ss ? ss : rs;
byte[] buf = new byte[BUF_SIZE];
initClientServerConnections(this.clientSocket);
String headerStr;
if (this.config.getProxySettings() == null)
headerStr = stripProxyInfoFromRequestHeader();
else
headerStr = this.header.toString();
log.trace("read request header");
byte[] bytes = headerStr.getBytes();
this.serverOut.write(bytes, 0, bytes.length);
log.trace("wrote request header");
byte[] requestBody;
if (this.header.contentLength > 0) {
this.buffer.reset();
int len = 0;
int num = 0;
while (num < this.header.contentLength) {
try {
len = this.clientIn.read(buf, 0, buf.length);
} catch (SocketException e) {
log.info("truncated request from browser: "
+ e.getMessage());
throw new Utils.SilentException();
}
if (len == 0)
break;
log.trace("read " + Integer.toString(len) + " bytes");
this.serverOut.write(buf, 0, len);
this.buffer.write(buf, 0, len);
log.trace("wrote " + Integer.toString(len) + " bytes");
num += len;
}
requestBody = this.buffer.toByteArray();
log.trace("transferred rest of request body");
} else {
requestBody = new byte[0];
log.trace("no request body");
}
this.clientSocket.shutdownInput();
this.serverSocket.shutdownOutput();
synchronized (mutex) {
this.proxyServer.processRequest(this.header, requestBody);
log.trace("processed request");
this.buffer.reset();
int len;
while ((len = this.serverIn.read(buf, 0, buf.length)) > 0) {
log.trace("read " + Integer.toString(len));
try {
this.clientOut.write(buf, 0, len);
} catch (SocketException e) {
log.info("browser stopped listening: "
+ e.getMessage() + this.buffer.toString());
throw new Utils.SilentException();
}
this.buffer.write(buf, 0, len);
}
log.trace("transferred response");
this.proxyServer.processResponse(this.header,
this.buffer.toByteArray());
log.trace("processed response");
}
} finally {
if (this.serverSocket != null) {
this.serverSocket.close();
log.trace("closed server socket");
}
this.clientSocket.close();
log.trace("closed client socket");
}
if (this.serverSocket != null) {
this.serverSocket.close();
log.trace("closed server socket");
}
this.clientSocket.close();
log.trace("closed client socket");
} catch (Throwable localThrowable) {
}
}
}

View File

@ -0,0 +1,131 @@
package org.bench4q.master.entity.httpcapture;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import org.bench4q.master.entity.httpcapture.generator.GeneratorFactory;
import org.bench4q.master.entity.httpcapture.generator.IScriptGenerator;
public class Test {
private IScriptGenerator generator;
private IScriptAdapter scriptAdapter;
private boolean isRecording;
private File testFile;
private String testName;
ProxyServer proxyServer;
public Test(ProxyServer proxy, IScriptAdapter adapter, String generatorClass) {
this.proxyServer = proxy;
adapter.setText("");
this.generator = GeneratorFactory.newGenerator(generatorClass, adapter);
this.generator.doNew();
this.scriptAdapter = adapter;
}
public Test(ProxyServer proxy, IScriptAdapter adapter, File file)
throws IOException, Utils.UserException {
this.proxyServer = proxy;
this.testFile = file;
StringBuffer buffer = new StringBuffer();
BufferedReader r = new BufferedReader(new FileReader(this.testFile));
String line = r.readLine();
while (line != null) {
buffer.append(line);
buffer.append(IScriptGenerator.EOL);
line = r.readLine();
}
r.close();
String script = buffer.toString();
String generatorClass = null;
String[] classes = GeneratorFactory.getClasses();
for (int i = 0; i < classes.length; i++) {
if (script.indexOf(classes[i]) != -1) {
generatorClass = classes[i];
break;
}
}
if (generatorClass == null) {
throw new Utils.UserException(
"Your file does not appear to have been generated by MaxQ.\n\n(MaxQ expects to find the class name of the generator somewhere in the script.\nPerhaps you have mistakenly deleted it?)");
}
adapter.setText(script);
this.generator = GeneratorFactory.newGenerator(generatorClass, adapter);
this.generator.doLoad();
this.testName = this.generator.parseTestName();
}
public String getTestName() {
return this.testName;
}
public File getTestFile() {
return this.testFile;
}
public void setTestFile(File file) {
this.testFile = file;
}
public String getCurrentPath() {
if (this.testFile == null) {
return System.getProperty("user.dir");
}
return stripFileName(this.testFile.getAbsolutePath());
}
public String[] getvalidTestFileExtensions() {
return this.generator.getValidFileExtensions();
}
public boolean isRecording() {
return this.isRecording;
}
public void stopRecording() {
this.proxyServer.removeObserver(this.generator);
assert (this.isRecording);
this.generator.doStopRecording();
this.isRecording = false;
}
public void startRecording() {
assert (!this.isRecording);
this.proxyServer.addObserver(this.generator);
this.isRecording = true;
this.generator.doStartRecording();
}
public boolean save() throws IOException {
return this.generator.doSave(
stripFileName(this.testFile.getAbsolutePath()),
this.testFile.getName());
}
private String stripFileName(String absolutePath) {
int index = absolutePath.lastIndexOf(System
.getProperty("file.separator"));
if (index == -1) {
return absolutePath;
}
return absolutePath.substring(0, index);
}
public void close() {
if (this.isRecording)
this.proxyServer.removeObserver(this.generator);
this.generator.close();
}
public IScriptGenerator getGenerator() {
return this.generator;
}
public String getScriptContent() {
return this.scriptAdapter.getText();
}
}

View File

@ -0,0 +1,122 @@
package org.bench4q.master.entity.httpcapture;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bench4q.master.entity.httpcapture.Param;
public class Utils {
public static final String SPACE = " ";
private static final Log log = LogFactory.getLog(Utils.class);
public static File saveHTML(String htmlFileName, String str, String dir_str)
{
if (str == null) {
log.error("Argument is null: EditorPane.saveHTML()");
return null;
}
File dir, htmlFile;
if (dir_str == null){
dir = new File("Tempfiles");
}
else {
dir = new File(dir_str);
}
dir.mkdir();
try
{
htmlFile = new File(dir, htmlFileName);
if (htmlFile.exists()) {
htmlFile.delete();
log.warn("deleting duplicated file: " + htmlFileName);
}
htmlFile.createNewFile();
PrintWriter writer = new PrintWriter(new FileWriter(htmlFile));
writer.print(str);
writer.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
return htmlFile;
}
public static String[] splitString(String str, String delim)
{
StringTokenizer st = new StringTokenizer(str, delim);
String[] res = new String[st.countTokens()];
int i = 0;
while (st.hasMoreTokens()) {
res[i] = st.nextToken();
i++;
}
return res;
}
public static String replace(String str, String search, String replace)
{
int pos = str.indexOf(search);
if (pos == -1) return str;
StringBuffer buff = new StringBuffer(str.length() + 32);
int start = 0;
while ((pos != -1) && (start < str.length())) {
buff.append(str.substring(start, pos));
buff.append(replace);
start = pos + search.length();
if (start < str.length()) pos = str.indexOf(search, start);
}
if (start < str.length()) buff.append(str.substring(start));
return buff.toString();
}
public static List<Param> getParams(String query)
{
List<Param> paramList = new ArrayList<Param>();
if (query != null) {
query = query.trim();
log.debug(" parsing: " + query);
String[] items = splitString(query, "&");
for (int i = 0; i < items.length; i++) {
int pos = items[i].indexOf("=");
if (pos != -1) {
Param p = new Param();
paramList.add(p);
p.name = items[i].substring(0, pos);
if (pos < items[i].length() - 1)
p.value = items[i].substring(pos + 1);
else
p.value = "";
}
}
}
return paramList;
}
public static class SilentException extends Exception
{
private static final long serialVersionUID = 3172942039967787899L;
public SilentException()
{
super();
}
}
public static class UserException extends Exception
{
private static final long serialVersionUID = -7337004995296463936L;
public UserException(String s)
{
super();
}
}
}

View File

@ -0,0 +1,574 @@
package org.bench4q.master.entity.httpcapture.generator;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.bench4q.master.communication.agent.RunScenarioModel;
import org.bench4q.master.communication.agent.UserBehaviorModel;
import org.bench4q.master.entity.httpcapture.Action;
import org.bench4q.master.entity.httpcapture.Config;
import org.bench4q.master.entity.httpcapture.HeaderValue;
import org.bench4q.master.entity.httpcapture.HttpRequestHeader;
import org.bench4q.master.entity.httpcapture.HttpTestCase;
import org.bench4q.master.entity.httpcapture.IScriptAdapter;
import org.bench4q.master.entity.httpcapture.Param;
import org.bench4q.master.entity.httpcapture.ProxyServer;
import org.bench4q.master.entity.httpcapture.Utils;
public abstract class AbstractCodeGenerator implements IScriptGenerator,
ProxyServer.Observer, Runnable {
private Config config = Config.getConfig();
private static final Log log;
private static String cpRspTo;
private static boolean cpRspToStdout;
private static boolean cpRspToFile;
private static final String[] MIME_DEFAULTS;
private static HashMap<String, String> mimeTypes;
protected static final String END_STATEMENT;
protected static String jtidyConfigFile;
protected long assertNumber = 0L;
protected boolean headersExist = false;
private IScriptAdapter scriptAdapter;
private String testName;
private String defaultTestName;
private String testPath;
private boolean ignoreNextResponse;
private Pattern[] namePatterns;
private LinkedList<UserBehaviorModel> outstandingInserts;
private Thread insertThread;
private String charset;
private long timeElapsedSinceLastestRequest = 0L;
private Date latestRequestDate = new Date();
private boolean isFirstRequest = true;
static final boolean $assertionsDisabled = !(AbstractCodeGenerator.class
.desiredAssertionStatus());
public static boolean isCpRspToStdout() {
return cpRspToStdout;
}
public static boolean isCpRspToFile() {
return cpRspToFile;
}
public AbstractCodeGenerator(IScriptAdapter adapter, String[] nameRegExps) {
this.scriptAdapter = adapter;
this.namePatterns = new Pattern[nameRegExps.length];
for (int i = 0; i < nameRegExps.length; ++i)
this.namePatterns[i] = Pattern.compile(nameRegExps[i], 8);
this.testName = this.config.getProperty("test.default_testname",
"Bench4QTest");
this.defaultTestName = this.testName;
this.insertThread = new Thread(this);
this.insertThread.start();
}
public String getDefaultTestName() {
return this.defaultTestName;
}
public void setDefaultTestName(String defaultTestName) {
this.defaultTestName = defaultTestName;
}
public IScriptAdapter getScriptAdapter() {
return this.scriptAdapter;
}
public String getTestName() {
return this.testName;
}
public void setTestName(String testName) {
this.testName = testName;
}
public String getTestPath() {
return this.testPath;
}
public void setTestPath(String testPath) {
this.testPath = testPath;
}
public long getTimeElapsedSinceLastestRequest() {
return this.timeElapsedSinceLastestRequest;
}
public boolean isFirstRequest() {
return this.isFirstRequest;
}
public String parseTestName() {
return this.testName;
}
public boolean doSave(String path, String fileName) {
String name = fileName;
int dotPos = fileName.indexOf(".");
RunScenarioModel runScenarioModel = this.scriptAdapter
.getRunScenarioModel();
FileWriter fileWriter;
if (dotPos > -1)
name = fileName.substring(0, dotPos);
setTestName(name);
setTestPath(path);
if (runScenarioModel == null) {
runScenarioModel = new RunScenarioModel();
}
try {
fileWriter = new FileWriter(new File(path + "\\" + fileName));
Marshaller marshaller = JAXBContext.newInstance(
runScenarioModel.getClass()).createMarshaller();
marshaller.marshal(runScenarioModel, fileWriter);
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
return true;
} catch (JAXBException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
public void doLoad() {
setTestName(parseTestName());
}
public void close() {
this.insertThread.interrupt();
}
public void processRequest(HttpRequestHeader header, byte[] requestBody)
throws Exception {
Param[] params;
int i;
String name;
String value;
Date d = new Date();
this.timeElapsedSinceLastestRequest = (d.getTime() - this.latestRequestDate
.getTime());
this.latestRequestDate = d;
if ((header.method.toLowerCase().equals("get"))
&& (urlIgnored(header.url))) {
log.debug("Ignoring GET request: \"" + header.url + "\"");
this.ignoreNextResponse = true;
return;
}
boolean isMultiPartRequest = header.contentType
.startsWith("multipart/form-data");
boolean isFormRequest = header.contentType
.startsWith("application/x-www-form-urlencoded");
Action action = new Action();
String newCharset = null;
Matcher charsetParser = Pattern.compile("charset=([a-z0-9_\\-]+)", 2)
.matcher(header.contentType);
if (charsetParser.matches()) {
newCharset = charsetParser.group();
if (!(newCharset.equals(this.charset))) {
doSetCharset(newCharset);
} else if (this.charset != null) {
doSetCharset(null);
}
}
doHeaders(createHeaders(header));
String url = header.url;
log.debug(" recording url: " + url);
String method = header.method.toLowerCase();
if (method.equals("get")) {
method = "Get";
} else if (method.equals("post")) {
method = "Post";
}
int pos = url.indexOf("?");
if ((pos != -1) && (url.length() > pos + 1)) {
setQueryStringParams(action, url.substring(pos + 1));
action.setUrl(url.substring(0, pos));
} else {
action.setUrl(url);
}
if (requestBody.length > 0) {
if (isMultiPartRequest) {
setMultiPartData(action, header, requestBody);
} else if (!(isFormRequest)) {
if (newCharset != null)
doSetData(new String(requestBody, newCharset));
else
doSetData(new String(requestBody));
} else if (newCharset != null)
setBodyParams(action, new String(requestBody, newCharset));
else {
setBodyParams(action, new String(requestBody));
}
}
if (action.getParamsCount() > 0) {
params = action.getParams();
for (i = 0; i < params.length; ++i) {
name = params[i].name;
value = params[i].value;
if ((name.indexOf("+") != -1) || (name.indexOf("%") != -1))
params[i].name = HttpTestCase.staticUrlDecode(name);
if ((value.indexOf("+") != -1) || (value.indexOf("%") != -1))
params[i].value = HttpTestCase.staticUrlDecode(value);
}
doParameterList(params);
}
if (action.getQueryStringParamCount() > 0) {
params = action.getQueryStringParams();
for (i = 0; i < params.length; ++i) {
name = params[i].name;
value = params[i].value;
if ((name.indexOf("+") != -1) || (name.indexOf("%") != -1))
params[i].name = HttpTestCase.staticUrlDecode(name);
if ((value.indexOf("+") != -1) || (value.indexOf("%") != -1))
params[i].value = HttpTestCase.staticUrlDecode(value);
}
doQueryStringParameterList(params);
}
if (action.getBodyParamCount() > 0) {
params = action.getBodyParams();
for (i = 0; i < params.length; ++i) {
name = params[i].name;
value = params[i].value;
if ((name.indexOf("+") != -1) || (name.indexOf("%") != -1))
params[i].name = HttpTestCase.staticUrlDecode(name);
if ((value.indexOf("+") != -1) || (value.indexOf("%") != -1))
params[i].value = HttpTestCase.staticUrlDecode(value);
}
doBodyParameterList(params);
}
String url_str = header.url;
if (requestBody.length > 0) {
url_str = url_str + '?' + new String(requestBody);
}
if (!(isMultiPartRequest)) {
doTestUrlMessage(HttpTestCase.staticUrlDecode(url_str).trim());
}
String data_str = "";
String cont_len_str = "";
if (isMultiPartRequest) {
method = method + "MultiPart";
data_str = ", data";
cont_len_str = ", " + header.contentLength;
doSetData(action.getMultiPartData());
}
doCallUrl(action.getUrl(), method, data_str, cont_len_str);
}
private HeaderValue[] createHeaders(HttpRequestHeader header) {
Vector<HeaderValue> v = new Vector<HeaderValue>();
if (header.contentType.length() > 0)
v.add(new HeaderValue("Content-Type", header.contentType));
if (header.accept.length() > 0)
v.add(new HeaderValue("Accept", header.accept));
if (header.referer.length() > 0)
v.add(new HeaderValue("Referer", header.referer));
if (header.pragmaNoCache)
v.add(new HeaderValue("Cache-Control", "no-cache"));
HeaderValue[] hv = new HeaderValue[v.size()];
return ((HeaderValue[]) (HeaderValue[]) v.toArray(hv));
}
public void processResponse(HttpRequestHeader header, byte[] response)
throws Exception {
if (this.ignoreNextResponse) {
log.debug("Ignoring response");
this.ignoreNextResponse = false;
return;
}
String respStr = new String(response).toLowerCase();
String respCode = parseResponseCode(respStr);
String contentType = parseContentType(respStr);
doAssertResponse(respCode);
if ((contentType != null) && (mimeTypes.get(contentType) != null)
&& (respCode != null)) {
if (respCode.startsWith("200")) {
if (respStr.indexOf("org.apache.struts.taglib.html.token") > 0)
setStruts(true);
else
setStruts(false);
if (contentType.toLowerCase().compareTo("text/html") == 0) {
doTidyCode(HttpTestCase.staticUrlDecode(header.url));
if (cpRspToStdout)
doResponseForStdOut(HttpTestCase.staticUrlDecode(
header.url).trim());
else if (cpRspToFile)
doResponseForFile();
}
}
doEndTransaction();
} else {
log.debug("Ignoring response because content type is not known: "
+ contentType);
}
if (isFirstRequest())
this.isFirstRequest = false;
}
public void run() {
this.outstandingInserts = new LinkedList<UserBehaviorModel>();
try {
while (!(Thread.interrupted())) {
synchronized (this.outstandingInserts) {
this.outstandingInserts.wait();
while (this.outstandingInserts.size() > 0) {
UserBehaviorModel userBehaviorModel = this.outstandingInserts
.removeFirst();
this.getScriptAdapter().insertUserBehaviorsToScenario(
userBehaviorModel);
}
}
}
} catch (InterruptedException e) {
log.trace("Thread dead");
}
}
public abstract void doAssertResponse(String paramString)
throws Utils.UserException;
public abstract void doCallUrl(String paramString1, String paramString2,
String paramString3, String paramString4)
throws Utils.UserException;
public abstract void doEndTransaction() throws Utils.UserException;
public abstract void setStruts(boolean paramBoolean);
public abstract void doSetCharset(String paramString)
throws Utils.UserException;
public abstract void doParameterList(Param[] paramArrayOfParam)
throws Utils.UserException;
public abstract void doQueryStringParameterList(Param[] paramArrayOfParam)
throws Utils.UserException;
public abstract void doBodyParameterList(Param[] paramArrayOfParam)
throws Utils.UserException;
public abstract void doResponseForFile() throws Utils.UserException;
public abstract void doResponseForStdOut(String paramString)
throws Utils.UserException;
public abstract void doSetData(String paramString)
throws Utils.UserException;
public abstract void doTestUrlMessage(String paramString)
throws Utils.UserException;
public abstract void doTidyCode(String paramString)
throws Utils.UserException;
public abstract void doHeaders(HeaderValue[] paramArrayOfHeaderValue);
protected void insert(UserBehaviorModel userBehaviorModel)
throws Utils.UserException {
synchronized (this.outstandingInserts) {
this.outstandingInserts.add(userBehaviorModel);
this.outstandingInserts.notifyAll();
}
}
private String parseContentType(String response) {
String contentType = null;
int pos = response.indexOf("content-type:");
if (pos > -1) {
pos += 14;
int end = response.indexOf("\r\n", pos);
int end2 = response.indexOf(";", pos);
if ((end2 > -1) && (end2 < end))
end = end2;
if (end > -1)
contentType = response.substring(pos, end).trim();
log.debug(" Content-Type: " + contentType);
} else {
log.debug(" No content-type header! First few lines:");
StringTokenizer st = new StringTokenizer(response, "\n");
int i = 0;
while ((st.hasMoreTokens()) && (i < 5)) {
log.debug(st.nextToken());
++i;
}
}
return contentType;
}
private String parseResponseCode(String response) {
String respCode = null;
int pos = response.indexOf(" ");
if (pos != -1) {
int end = response.indexOf(" ", pos + 1);
int end2 = response.indexOf("\n", pos + 1);
if ((end2 != -1) && (end2 < end))
end = end2;
if (end != -1)
respCode = response.substring(pos + 1, end).trim();
}
log.debug("HTTP response code: " + respCode);
return respCode;
}
private void setMultiPartData(Action action, HttpRequestHeader header,
byte[] strarray) {
String str = new String(strarray);
int begin = header.contentType.indexOf("boundary=");
int end = header.contentType.indexOf("; ", begin);
if (end == -1)
end = header.contentType.length();
String boundary = header.contentType.substring(begin + 9, end);
String[] parts = str.split("--" + boundary);
if ((!($assertionsDisabled)) && (!(parts[0].equals(""))))
throw new AssertionError();
Pattern re = Pattern
.compile(
"\r\nContent-Disposition: form-data; name=\"([^\"]+)\"[^\r\n]*\r\n\r\n(.*)\r\n",
32);
for (int i = 1; i < parts.length - 1; ++i) {
Matcher m = re.matcher(parts[i]);
boolean ok = m.matches();
if ((!($assertionsDisabled)) && (!(ok)))
throw new AssertionError();
Param p = new Param();
p.name = m.group(1);
p.value = m.group(2);
action.addBodyParam(p);
}
if ((!($assertionsDisabled))
&& (!(parts[(parts.length - 1)].equals("--\r\n"))))
throw new AssertionError();
}
private void setQueryStringParams(Action action, String str) {
List<Param> params = Utils.getParams(str);
Iterator<Param> iter = params.iterator();
while (iter.hasNext())
action.addQueryStringParam((Param) iter.next());
}
private void setBodyParams(Action action, String str) {
List<Param> params = Utils.getParams(str);
Iterator<Param> iter = params.iterator();
while (iter.hasNext())
action.addBodyParam((Param) iter.next());
}
private boolean urlIgnored(String str) {
boolean ignore = false;
List<Pattern> incPats = this.config.getIncludePatterns();
List<Pattern> excPats = this.config.getExcludePatterns();
if ((!(ignore)) && (incPats.size() != 0)) {
log.debug("urlIgnored: checking for include matches");
ignore = this.checkMatch(incPats.iterator(), str, false, true);
}
if ((!(ignore)) && (excPats.size() != 0)) {
log.debug("urlIgnored: checking for exclude matches");
ignore = this.checkMatch(excPats.iterator(), str, true, ignore);
}
return ignore;
}
private boolean checkMatch(Iterator<Pattern> iter, String str, boolean res,
boolean def) {
while (iter.hasNext()) {
Matcher m = ((Pattern) iter.next()).matcher(str);
log.debug("checkMatch: for \"" + str + "\" with pattern: \""
+ m.pattern().pattern() + "\"");
if (m.find()) {
log.debug("checkMatch: Found match, returning: " + res);
return res;
}
}
log.debug("checkMatch: Didn't find match, returning: " + def);
return def;
}
static {
log = LogFactory.getLog(AbstractCodeGenerator.class);
cpRspTo = System.getProperty("http.cpRspTo");
cpRspToFile = false;
MIME_DEFAULTS = new String[] { "text/plain", "text/html",
"text/comma-separated-values" };
END_STATEMENT = ";" + EOL;
jtidyConfigFile = System.getProperty("jtidy.config");
if (cpRspTo != null)
if (cpRspTo.toLowerCase().compareTo("stdout") == 0)
cpRspToStdout = true;
else if (cpRspTo.toLowerCase().compareTo("file") == 0)
cpRspToFile = true;
mimeTypes = new HashMap<String, String>();
for (int i = 0; i < MIME_DEFAULTS.length; ++i)
mimeTypes.put(MIME_DEFAULTS[i], MIME_DEFAULTS[i]);
}
}

View File

@ -0,0 +1,297 @@
package org.bench4q.master.entity.httpcapture.generator;
import java.util.ArrayList;
import java.util.List;
import org.bench4q.master.communication.agent.ParameterModel;
import org.bench4q.master.communication.agent.UsePluginModel;
import org.bench4q.master.communication.agent.UserBehaviorModel;
import org.bench4q.master.entity.httpcapture.Config;
import org.bench4q.master.entity.httpcapture.HeaderValue;
import org.bench4q.master.entity.httpcapture.IScriptAdapter;
import org.bench4q.master.entity.httpcapture.Param;
import org.bench4q.master.entity.httpcapture.Utils;
public class Bench4qCodeGenerator extends AbstractCodeGenerator {
static final String TIMER_PROP = "generator.isac.timer";
static final String NULL_TIMER = "null";
static final String CONSTANT_TIMER = "ConstantTimer";
static final String RANDOM_TIMER = "Random";
static final String DEFAULT_TIMER = "ConstantTimer";
static final String RANDOM_TIMER_DIST_PROP = "generator.isac.timer.random.dist";
static final String RANDOM_TIMER_DIST_UNIFORM = "uniform";
static final String RANDOM_TIMER_DIST_GAUSSIAN = "gaussian";
static final String RANDOM_TIMER_DIST_POISSON = "poisson";
static final String RANDOM_TIMER_DIST_NEGEXPO = "negexpo";
static final String RANDOM_TIMER_DIST_DEFAULT = "uniform";
static final String RANDOM_TIMER_MIN_PROP = "generator.isac.timer.random.min";
static final String RANDOM_TIMER_DELTA_PROP = "generator.isac.timer.random.delta";
static final String RANDOM_TIMER_UNIT_PROP = "generator.isac.timer.random.unit";
static final String RANDOM_TIMER_DEVIATION_PROP = "generator.isac.timer.random.deviation";
static final String[][] escapes = { { "\\", "\\\\" }, { ";", "\\;" },
{ "&", "&amp;" }, { "\"", "&quot;" }, { "<", "&lt;" },
{ ">", "&gt;" } };
private String queryStringParameters = "";
private String bodyParameters = "";
private String timer;
private String randomDist;
private int delta = 0;
private int deviation = 0;
private int unit = 1;
private static String escapeXmlString(String str) {
for (int i = 0; i < escapes.length; ++i)
str = str.replace(escapes[i][0], escapes[i][1]);
return str;
}
private static String encodedParameterList(Param[] params) {
String result = "";
for (int i = 0; i < params.length; ++i) {
if (i > 0)
result = result + ";";
result = result + escapeXmlString(params[i].name) + "="
+ escapeXmlString(params[i].value);
}
return result;
}
public Bench4qCodeGenerator(IScriptAdapter adapter) {
super(adapter, new String[0]);
}
public static String getGeneratorDescription() {
return "ISAC scenario for CLIF.ow2.org";
}
public void doNew() {
List<UsePluginModel> usePlugins = new ArrayList<UsePluginModel>();
UsePluginModel usePlugin1 = new UsePluginModel();
UsePluginModel usePlugin2 = new UsePluginModel();
usePlugin1.setParameters(new ArrayList<ParameterModel>());
usePlugin1.setId("http");
usePlugin1.setName("Http");
usePlugin2.setId("timer");
usePlugin2.setParameters(new ArrayList<ParameterModel>());
Config conf = Config.getConfig();
this.timer = conf.getProperty("generator.isac.timer", "ConstantTimer");
if (this.timer.equals("ConstantTimer")) {
usePlugin2.setName("ConstantTimer");
} else if (this.timer.equals("Random")) {
usePlugin2.setName("Random");
this.randomDist = Config.getConfig().getProperty(
"generator.isac.timer.random.dist", "uniform");
try {
if (this.randomDist.equals("uniform")) {
this.delta = conf.getPropertyInt(
"generator.isac.timer.random.delta").intValue();
} else if (this.randomDist.equals("gaussian")) {
this.delta = conf.getPropertyInt(
"generator.isac.timer.random.delta").intValue();
this.deviation = conf.getPropertyInt(
"generator.isac.timer.random.deviation").intValue();
} else if (this.randomDist.equals("poisson")) {
this.unit = conf.getPropertyInt(
"generator.isac.timer.random.unit").intValue();
} else if (!(this.randomDist.equals("negexpo"))) {
} else {
this.delta = conf.getPropertyInt(
"generator.isac.timer.random.delta").intValue();
}
} catch (Utils.UserException ex) {
ex.printStackTrace(System.err);
System.err
.println("Warning: incorrect property settings for Isac random timer distribution "
+ this.randomDist);
}
}
usePlugins.add(usePlugin1);
usePlugins.add(usePlugin2);
appendUserPluginsToScenario(usePlugins);
}
public String[] getValidFileExtensions() {
return new String[] { ".xis" };
}
public void doParameterList(Param[] params) throws Utils.UserException {
}
public void doQueryStringParameterList(Param[] params)
throws Utils.UserException {
this.queryStringParameters = encodedParameterList(params);
}
public void doBodyParameterList(Param[] params) throws Utils.UserException {
this.bodyParameters = encodedParameterList(params);
}
public void doTestUrlMessage(String url) {
}
public void doSetData(String data) {
}
public void doCallUrl(String url, String method, String data,
String contentLength) throws Utils.UserException {
if (!(isFirstRequest()))
doInsertDelay(getTimeElapsedSinceLastestRequest());
UserBehaviorModel userBehavior = createUserBehavior(url, method);
insertStmt(userBehavior);
this.queryStringParameters = "";
this.bodyParameters = "";
}
private UserBehaviorModel createUserBehavior(String url, String method) {
UserBehaviorModel userBehavior = new UserBehaviorModel();
ParameterModel param1 = new ParameterModel();
ParameterModel param3 = new ParameterModel();
List<ParameterModel> params = new ArrayList<ParameterModel>();
param1.setKey("url");
param1.setValue(url);
param3.setKey("parameters");
param3.setValue(this.queryStringParameters);
params.add(param1);
params.add(param3);
if (method.equalsIgnoreCase("post")) {
ParameterModel param2 = new ParameterModel();
param2.setKey("bodyparameters");
param2.setValue(this.bodyParameters);
params.add(param2);
}
userBehavior.setName(method);
userBehavior.setUse("http");
userBehavior.setParameters(params);
return userBehavior;
}
public void doAssertResponse(String respCode) {
}
public void doTidyCode(String url) {
}
public void doResponseForStdOut(String url) {
}
public void doResponseForFile() {
}
public void doEndTransaction() throws Utils.UserException {
}
public void doStartRecording() {
}
public void doStopRecording() {
}
public void doClose() {
}
public void setStruts(boolean struts) {
}
public void doHeaders(HeaderValue[] headers) {
}
private void appendUserPluginsToScenario(List<UsePluginModel> usePlugins) {
this.getScriptAdapter().appendUsePluginsToScenario(usePlugins);
}
private void insertStmt(UserBehaviorModel userBehaviorModel)
throws Utils.UserException {
insert(userBehaviorModel);
}
private void doInsertDelay(long delay) throws Utils.UserException {
StringBuilder timerStr = new StringBuilder();
timerStr = createTimer(delay);
System.out.println(timerStr);
// insertStmt(timerStr.toString());
}
private StringBuilder createTimer(long delay) {
StringBuilder timerStr = new StringBuilder();
if (this.timer.equals("Random")) {
int min = (int) (delay - this.delta);
if (min < 0)
min = 0;
if (this.randomDist.equals("uniform")) {
timerStr.append("\t\t\t<control use=\"replayTimer\" name=\"setUniform\">"
+ EOL);
timerStr.append("\t\t\t\t<params>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"min\" value=\"" + min
+ "\"/>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"max\" value=\""
+ (delay + this.delta) + "\"/>" + EOL);
timerStr.append("\t\t\t\t</params>" + EOL);
timerStr.append("\t\t\t</control>" + EOL);
} else if (this.randomDist.equals("gaussian")) {
timerStr.append("\t\t\t<control use=\"replayTimer\" name=\"setGaussian\">"
+ EOL);
timerStr.append("\t\t\t\t<params>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"min\" value=\"" + min
+ "\"/>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"max\" value=\""
+ (delay + this.delta) + "\"/>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"mean\" value=\""
+ delay + "\"/>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"deviation\" value=\""
+ this.deviation + "\"/>" + EOL);
timerStr.append("\t\t\t\t</params>" + EOL);
timerStr.append("\t\t\t</control>" + EOL);
} else if (this.randomDist.equals("poisson")) {
timerStr.append("\t\t\t<control use=\"replayTimer\" name=\"setPoisson\">"
+ EOL);
timerStr.append("\t\t\t\t<params>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"unit\" value=\""
+ this.unit + "\"/>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"parameter\" value=\""
+ delay + "\"/>" + EOL);
timerStr.append("\t\t\t\t</params>" + EOL);
timerStr.append("\t\t\t</control>" + EOL);
} else if (this.randomDist.equals("negexpo")) {
timerStr.append("\t\t\t<control use=\"replayTimer\" name=\"setNegativeExpo\">"
+ EOL);
timerStr.append("\t\t\t\t<params>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"min\" value=\"" + min
+ "\"/>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"mean\" value=\""
+ delay + "\"/>" + EOL);
timerStr.append("\t\t\t\t</params>" + EOL);
timerStr.append("\t\t\t</control>" + EOL);
}
timerStr.append("\t\t\t<timer use=\"replayTimer\" name=\"sleep\"/>"
+ EOL);
} else if (this.timer.equals("ConstantTimer")) {
timerStr.append("\t\t\t<timer use=\"replayTimer\" name=\"sleep\">"
+ EOL);
timerStr.append("\t\t\t\t<params>" + EOL);
timerStr.append("\t\t\t\t\t<param name=\"duration_arg\" value=\""
+ delay + "\"></param>" + EOL);
timerStr.append("\t\t\t\t</params>" + EOL);
timerStr.append("\t\t\t</timer>" + EOL);
}
return timerStr;
}
public void doSetCharset(String cs) throws Utils.UserException {
}
}

View File

@ -0,0 +1,68 @@
package org.bench4q.master.entity.httpcapture.generator;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.bench4q.master.entity.httpcapture.Config;
import org.bench4q.master.entity.httpcapture.Utils;
import org.bench4q.master.entity.httpcapture.IScriptAdapter;
public class GeneratorFactory {
private static Config config = Config.getConfig();
public static final String GENERATOR_CLASSNAMES_PROPERTY = "generator.classnames";
public static final String JYTHON_CLASSNAME = "com.bitmechanic.maxq.generator.JythonCodeGenerator";
public static String[] getClasses()
{
String names = config.getProperty("generator.classnames",
"com.bitmechanic.maxq.generator.JythonCodeGenerator");
return Utils.splitString(names, ":");
}
public static String getClassDescription(String className)
throws ClassNotFoundException, IllegalAccessException, InvocationTargetException
{
Method getGenDesc;
Class<?> gen = Class.forName(className);
try
{
getGenDesc = gen.getMethod("getGeneratorDescription", gen);
}
catch (NoSuchMethodException e)
{
return className;
}
return (String)getGenDesc.invoke((Object)null, (Object)null);
}
public static IScriptGenerator newGenerator(String className, IScriptAdapter adapter)
{
Class<?> clazz = null;
try {
clazz = GeneratorFactory.class.getClassLoader().loadClass(className);
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Invalid test script class specified . Class not found:" + className);
}
if (IScriptGenerator.class.isAssignableFrom(clazz)) {
try {
Class<?>[] generatorConstructorParameterClasses = { IScriptAdapter.class };
Object[] generatorConstructorParameters = { adapter };
Constructor<?> constructor = clazz.getDeclaredConstructor(generatorConstructorParameterClasses);
return (IScriptGenerator)constructor.newInstance(generatorConstructorParameters);
}
catch (NoSuchMethodException e) {
throw new IllegalStateException("Invalid test script class specified. Must have a constructor that takes in properties: " + className);
} catch (InstantiationException e) {
throw new IllegalStateException("Invalid test script class specified. Could not construct: " + className);
} catch (InvocationTargetException e) {
e.printStackTrace();
throw new IllegalStateException("Invalid test script class specified. Exception thrown in constructor: " + className);
} catch (IllegalAccessException e) {
throw new IllegalStateException("Invalid test script class specified. IllegalAccessException: " + className);
}
}
throw new IllegalStateException("Invalid test script class specified. Does not implement IScriptGenerator: " + className);
}
}

View File

@ -0,0 +1,23 @@
package org.bench4q.master.entity.httpcapture.generator;
import org.bench4q.master.entity.httpcapture.ProxyServer;
public interface IScriptGenerator extends ProxyServer.Observer {
public static final String EOL = System.getProperty("line.separator");
public abstract String[] getValidFileExtensions();
public abstract String parseTestName();
public abstract void doStartRecording();
public abstract void doStopRecording();
public abstract void doNew();
public abstract boolean doSave(String paramString1, String paramString2);
public abstract void doLoad();
public abstract void close();
}

View File

@ -0,0 +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;
}
}
}

View File

@ -0,0 +1,57 @@
package org.bench4q.master.helper;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class MashalHelper {
private Marshaller marshaller;
private Unmarshaller unmarshaller;
private Class<?> class1;
public MashalHelper(String className) throws ClassNotFoundException,
JAXBException {
this.setClass1(Class.forName(className));
this.setMarshaller(JAXBContext.newInstance(this.getClass1())
.createMarshaller());
this.setUnmarshaller(JAXBContext.newInstance(this.getClass1())
.createUnmarshaller());
}
public Marshaller getMarshaller() {
return marshaller;
}
public void setMarshaller(Marshaller marshaller) {
this.marshaller = marshaller;
}
public Unmarshaller getUnmarshaller() {
return unmarshaller;
}
public void setUnmarshaller(Unmarshaller unmarshaller) {
this.unmarshaller = unmarshaller;
}
public Class<?> getClass1() {
return class1;
}
public void setClass1(Class<?> class1) {
this.class1 = class1;
}
public String marshallXmlObjectToString(Object object) throws JAXBException {
StringWriter stringWriter = new StringWriter();
this.getMarshaller().marshal(object, stringWriter);
return stringWriter.toString();
}
}

View File

@ -0,0 +1,37 @@
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

@ -0,0 +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;
}
}

View File

@ -0,0 +1,267 @@
package org.bench4q.master.service;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.bench4q.master.communication.HttpRequester;
import org.bench4q.master.communication.HttpRequester.HttpResponse;
import org.bench4q.master.communication.agent.RunScenarioResultModel;
import org.bench4q.master.entity.db.Agent;
import org.bench4q.master.helper.SessionHelper;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class AgentService {
public static int AGENT_STATUS_Idel = 1;
public static int AGENT_STATUS_InRun = 2;
public static int AGENT_STATUS_BackUp = 3;
public static int AGENT_STATUS_BreakDown = 4;
private SessionHelper sessionHelper = new SessionHelper();
private Object AGENT_LOCK = new Object();
private HttpRequester httpRequester;
public static final int PORT = 6565;
public AgentService() {
this.setAgentLock(new Object());
}
private SessionHelper getSessionHelper() {
return sessionHelper;
}
@Autowired
private void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
public Object getAgentLock() {
return AGENT_LOCK;
}
public void setAgentLock(Object object) {
this.AGENT_LOCK = object;
}
public HttpRequester getHttpRequester() {
return httpRequester;
}
@Autowired
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
public boolean addAgentToPool(Agent agentInParam) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Agent agent = (Agent) session
.createCriteria(Agent.class)
.add(Restrictions.eq("hostName", agentInParam.getHostName()))
.uniqueResult();
if (agent != null) {
return false;
}
agent = new Agent();
agent.setHostName(agentInParam.getHostName());
agent.setMaxLoad(agentInParam.getMaxLoad());
agent.setPort(agentInParam.getPort());
agent.setRemainLoad(agentInParam.getRemainLoad());
agent.setCurrentStatus(AGENT_STATUS_Idel);
session.merge(agent);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean removeAgentFromPool(String hostNameString) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Agent agent = (Agent) session.createCriteria(Agent.class)
.add(Restrictions.eq("hostName", hostNameString))
.uniqueResult();
if (agent == null) {
return false;
}
session.delete(agent);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean recomputeRemainLoadOfAgent(Agent agent) {
return false;
}
public List<Agent> loadAgentPoolFromDB() {
return this._getAgentList();
}
@SuppressWarnings("unchecked")
private List<Agent> _getAgentList() {
List<Agent> agentList = null;
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
agentList = session.createCriteria(Agent.class)
.addOrder(Order.desc("remainLoad")).list();
transaction.commit();
return agentList;
} catch (Exception e) {
e.printStackTrace();
return agentList;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean backLoadToAgent(String hostName, int backLoad) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Agent agent = (Agent) session.createCriteria(Agent.class)
.add(Restrictions.eq("hostName", hostName)).uniqueResult();
if (agent == null) {
return false;
}
agent.setRemainLoad(agent.getRemainLoad() + backLoad);
session.merge(agent);
transaction.commit();
System.out.println(agent.getRemainLoad());
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean getLoadFromAgent(String hostName, int requireLoad) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Agent agent = (Agent) session.createCriteria(Agent.class)
.add(Restrictions.eq("hostName", hostName)).uniqueResult();
if (agent == null) {
return false;
}
agent.setRemainLoad(agent.getRemainLoad() - requireLoad);
session.merge(agent);
transaction.commit();
System.out.println(agent.getRemainLoad());
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean resetAgent(Agent agentInParam) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = sessionHelper.openSession()
.beginTransaction();
try {
Agent agentFromDB = (Agent) session
.createCriteria(Agent.class)
.add(Restrictions.eq("hostName", agentInParam.getHostName()))
.uniqueResult();
if (agentFromDB == null) {
return false;
}
agentFromDB.setRemainLoad(agentFromDB.getMaxLoad());
session.merge(agentFromDB);
transaction.commit();
return true;
} catch (Exception e) {
return false;
} finally {
session.close();
}
}
public boolean updateAgentStatus(int currentStatus, String hostName) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Agent agentFromDB = (Agent) session.createCriteria(Agent.class)
.add(Restrictions.eq("hostName", hostName)).uniqueResult();
if (agentFromDB == null) {
return false;
}
agentFromDB.setCurrentStatus(currentStatus);
session.merge(agentFromDB);
transaction.commit();
return true;
} catch (Exception e) {
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public RunScenarioResultModel run(Agent agent, String scriptContent) {
try {
HttpResponse httpResponse = this.httpRequester.sendPostXml(
agent.getHostName() + ":" + PORT + "/test/run",
scriptContent, null);
return extractRunSenarioResultModel(httpResponse.getContent());
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
private RunScenarioResultModel extractRunSenarioResultModel(
String responseContent) throws JAXBException {
RunScenarioResultModel resultModel = new RunScenarioResultModel();
Unmarshaller unmarshaller = JAXBContext.newInstance(
resultModel.getClass()).createUnmarshaller();
resultModel = (RunScenarioResultModel) unmarshaller
.unmarshal(new ByteArrayInputStream(responseContent.getBytes()));
return resultModel;
}
}

View File

@ -0,0 +1,168 @@
package org.bench4q.master.service;
import java.util.List;
import org.bench4q.master.entity.db.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();
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 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;
}
session.delete(portDB);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean existInDBPool(int port) {
Session session = this.getSessionHelper().openSession();
try {
Port portDB = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("port", port)).uniqueResult();
if (portDB == null) {
return false;
}
return true;
} catch (Exception e) {
e.printStackTrace();
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 backThePortToPool(int port) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Port portEntity = (Port) session.createCriteria(Port.class)
.add(Restrictions.eq("port", port)).uniqueResult();
if (portEntity == null) {
return false;
}
portEntity.setInUse(false);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return true;
} finally {
if (session != null) {
session.close();
}
}
}
@SuppressWarnings("unchecked")
public List<Port> loadPortList() {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
List<Port> ports = session.createCriteria(Port.class).list();
transaction.commit();
return ports;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
}

View File

@ -0,0 +1,195 @@
package org.bench4q.master.service;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.bench4q.master.communication.agent.RunScenarioModel;
import org.bench4q.master.communication.agent.UserBehaviorModel;
import org.bench4q.master.entity.db.Script;
import org.bench4q.master.entity.db.User;
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 ScriptService {
private SessionHelper sessionHelper = new SessionHelper();
private UserService userService;
private SessionHelper getSessionHelper() {
return sessionHelper;
}
@Autowired
private void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
public UserService getUserService() {
return userService;
}
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
public boolean saveScriptToDB(String scriptName, int userId,
String scriptContent) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
User user = this.getUserService().getUserById(userId);
Script script = new Script();
script.setName(scriptName);
script.setUser(user);
script.setCreateDateTime((new Date()));
script.setScriptContent(scriptContent);
script.setBehaviorCount(getScriptBehaviorsCount(scriptContent));
session.merge(script);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public Script getScriptById(int scriptId) {
Session session = this.sessionHelper.openSession();
try {
return (Script) session.createCriteria(Script.class)
.add(Restrictions.eq("id", scriptId)).uniqueResult();
} catch (Exception e) {
return null;
} finally {
if (session != null)
session.close();
}
}
private int getScriptBehaviorsCount(String scriptContent)
throws JAXBException {
int temp = 0;
List<UserBehaviorModel> behaviors = this.extractRunScenarioModel(
scriptContent).getUserBehaviors();
if (behaviors == null) {
temp = 0;
} else {
temp = behaviors.size();
}
return temp;
}
public int getScriptBehaviorCount(int scriptId) {
Session session = this.getSessionHelper().openSession();
try {
Script script = (Script) session.createCriteria(Script.class)
.add(Restrictions.eq("scriptId", scriptId)).uniqueResult();
if (script == null) {
return -1;
}
return script.getId();
} catch (Exception e) {
return -1;
} finally {
if (session != null) {
session.close();
}
}
}
public List<Script> loadScripts(User user) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
@SuppressWarnings("unchecked")
List<Script> scripts = session.createCriteria(Script.class)
.add(Restrictions.eq("user", user)).list();
if (scripts == null) {
return null;
}
transaction.commit();
return scripts;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
public List<Script> queryScriptsByCreateTime(Date startDate, Date endDate) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
@SuppressWarnings("unchecked")
List<Script> scripts = session
.createCriteria(Script.class)
.add(Restrictions.between("createDateTime", startDate,
endDate)).list();
if (scripts == null) {
return null;
}
transaction.commit();
return scripts;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
public RunScenarioModel getRunSceniroModelByScriptId(int scriptId) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
Script script = (Script) session.createCriteria(Script.class)
.add(Restrictions.eq("id", scriptId)).uniqueResult();
if (script == null) {
return null;
}
return extractRunScenarioModel(script.getScriptContent());
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
private RunScenarioModel extractRunScenarioModel(String content)
throws JAXBException {
RunScenarioModel runScenarioModel = new RunScenarioModel();
Unmarshaller unmarshaller;
unmarshaller = JAXBContext.newInstance(runScenarioModel.getClass())
.createUnmarshaller();
runScenarioModel = (RunScenarioModel) unmarshaller
.unmarshal(new ByteArrayInputStream(content.getBytes()));
return runScenarioModel;
}
}

View File

@ -0,0 +1,122 @@
package org.bench4q.master.service;
import java.util.Date;
import java.util.Iterator;
import org.bench4q.master.api.model.RunningScriptModel;
import org.bench4q.master.api.model.TestPlanConfig;
import org.bench4q.master.api.model.TestPlanModel;
import org.bench4q.master.entity.db.PlanConfig;
import org.bench4q.master.entity.db.TestPlan;
import org.bench4q.master.entity.db.TestPlanScript;
import org.bench4q.master.entity.db.User;
import org.bench4q.master.helper.SessionHelper;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TestPlanService {
private SessionHelper sessionHelper;
private ScriptService scriptService;
@Autowired
public void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
@Autowired
public void setScriptService(ScriptService scriptService) {
this.scriptService = scriptService;
}
public boolean saveTestPlanToDB(TestPlanModel testPlanModel, User user) {
TestPlan testPlanInDB = this.saveToTestPlan(testPlanModel.getName(),
user);
if (testPlanInDB == null) {
return false;
}
return this.saveToTestPlanScript(testPlanModel, testPlanInDB)
&& this.saveToPlanConfig(testPlanInDB, testPlanModel);
}
private TestPlan saveToTestPlan(String name, User user) {
Session session = this.sessionHelper.openSession();
Transaction transaction = session.beginTransaction();
TestPlan result = new TestPlan();
try {
TestPlan testPlan = new TestPlan();
testPlan.setCreateDateTime(new Date());
testPlan.setName(name);
testPlan.setUser(user);
result = (TestPlan) session.merge(testPlan);
transaction.commit();
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (session != null)
session.close();
}
}
private boolean saveToTestPlanScript(TestPlanModel testPlanModel,
TestPlan testPlan) {
Session session = this.sessionHelper.openSession();
Transaction transaction = session.beginTransaction();
TestPlanScript testPlanScript = new TestPlanScript();
RunningScriptModel runningScriptModel = new RunningScriptModel();
try {
Iterator<RunningScriptModel> iterator = testPlanModel
.getRunnningScriptModels().iterator();
while (iterator.hasNext()) {
runningScriptModel = iterator.next();
testPlanScript = new TestPlanScript();
testPlanScript.setTestPlan(testPlan);
testPlanScript.setScript(this.scriptService
.getScriptById(runningScriptModel.getScriptId()));
testPlanScript.setRequireLoad(runningScriptModel
.getRequireLoad());
session.merge(testPlanScript);
}
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (session != null)
session.close();
}
}
private boolean saveToPlanConfig(TestPlan testPlan,
TestPlanModel testPlanModel) {
Session session = this.sessionHelper.openSession();
Transaction transaction = session.beginTransaction();
try {
PlanConfig planConfig = new PlanConfig();
planConfig.setTestPlan(testPlan);
TestPlanConfig config = testPlanModel.getConfig();
if (config == null) {
return false;
}
planConfig.setWarmUp(config.getWarmUp());
planConfig.setExecuteRange(config.getExecuteRange());
planConfig.setCoolDown(config.getCoolDown());
session.merge(planConfig);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
}

View File

@ -0,0 +1,118 @@
package org.bench4q.master.service;
import org.bench4q.master.entity.db.User;
import org.bench4q.master.helper.HashHelper;
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 UserService {
private SessionHelper sessionHelper;
private HashHelper hashHelper;
public static byte NORAML_AUTHENTICATION = 0;
public static byte SUPER_AUTHENTICATION = 1;
private SessionHelper getSessionHelper() {
return sessionHelper;
}
@Autowired
public void setSessionHelper(SessionHelper sessionHelper) {
this.sessionHelper = sessionHelper;
}
private HashHelper getHashHelper() {
return hashHelper;
}
@Autowired
private void setHashHelper(HashHelper hashHelper) {
this.hashHelper = hashHelper;
}
public boolean register(String userName, String password) {
Session session = this.getSessionHelper().openSession();
Transaction transaction = session.beginTransaction();
try {
User user = (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", userName)).uniqueResult();
if (user != null) {
return false;
}
user = new User();
user.setUserName(userName);
user.setPassword(this.hashPassword(password));
user.setScope(UserService.NORAML_AUTHENTICATION);
session.merge(user);
transaction.commit();
return true;
} catch (Exception e) {
e.printStackTrace();
transaction.rollback();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public boolean validateUser(String userName, String password) {
Session session = this.getSessionHelper().openSession();
try {
User user = (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", userName)).uniqueResult();
if (user == null) {
return false;
}
if (user.getPassword().equals(this.hashPassword(password))) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (session != null) {
session.close();
}
}
}
public String hashPassword(String password) {
return this.getHashHelper().sha1Hash(password);
}
public User getUserByName(String userName) {
Session session = this.getSessionHelper().openSession();
try {
return (User) session.createCriteria(User.class)
.add(Restrictions.eq("userName", userName)).uniqueResult();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
public User getUserById(int userId) {
Session session = this.getSessionHelper().openSession();
try {
return (User) session.get(User.class, userId);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (session != null) {
session.close();
}
}
}
}

View File

@ -0,0 +1,84 @@
package org.bench4q.master.testPlan;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.UUID;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.bench4q.master.communication.HttpRequester;
import org.bench4q.master.communication.HttpRequester.HttpResponse;
import org.bench4q.master.communication.agent.StopTestModel;
import org.bench4q.master.service.AgentService;
public class ExecutionOverTask extends TimerTask {
private HttpRequester httpRequester;
private RunningAgentInfo runningAgentInfo;
private void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
public void setRunningAgentInfo(RunningAgentInfo runningAgentInfo) {
this.runningAgentInfo = runningAgentInfo;
}
public ExecutionOverTask() {
this.setHttpRequester(new HttpRequester());
}
@Override
public void run() {
if (this.runningAgentInfo == null) {
return;
}
Iterator<UUID> iterator = this.runningAgentInfo.getRunIdHostLoadMap()
.keySet().iterator();
while (iterator.hasNext()) {
UUID agentRunId = iterator.next();
stopAgentRunScenario(agentRunId,
this.runningAgentInfo.queryHostNameLoadScriptId(agentRunId));
}
System.out.println("execute ExecutionOverTask");
}
private void stopAgentRunScenario(UUID agentRunId,
HostNameLoadScriptId hostNameLoadScriptId) {
if (hostNameLoadScriptId == null) {
return;
}
try {
String url = hostNameLoadScriptId.getHostName() + ":"
+ AgentService.PORT + "/test/stop/" + agentRunId;
HttpResponse httpResponse = this.httpRequester.sendGet(url, null,
null);
if (httpResponse == null) {
return;
}
extractModel(httpResponse.getContent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
private StopTestModel extractModel(String content) {
StopTestModel result = new StopTestModel();
try {
Unmarshaller unmarshaller = JAXBContext.newInstance(
result.getClass()).createUnmarshaller();
result = (StopTestModel) unmarshaller
.unmarshal(new ByteArrayInputStream(content.getBytes()));
return result;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,197 @@
package org.bench4q.master.testPlan;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.bench4q.master.communication.AgentStateService;
import org.bench4q.master.communication.agent.ServerStatusModel;
import org.bench4q.master.entity.db.Agent;
import org.bench4q.master.service.AgentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
public class HighAvailableAgentPool {
private List<Agent> highAvailablePool;
private AgentService agentService;
private AgentStateService agentStateService;
private TaskQueueContainer taskQueueContainer;
private Map<String, ServerStatusModel> agentStatusOfPreviousBeatMap;
private long maxLoadOfHAPool;
public List<Agent> getHighAvailablePool() {
return this.highAvailablePool;
}
private void setHighAvailablePool(List<Agent> highAvailablePool) {
this.highAvailablePool = highAvailablePool;
}
@Autowired
public void setAgentService(AgentService agentService) {
this.agentService = agentService;
}
@Autowired
public void setAgentStateService(AgentStateService agentStateService) {
this.agentStateService = agentStateService;
}
@Autowired
public void setTaskQueueContainer(TaskQueueContainer taskQueueContainer) {
this.taskQueueContainer = taskQueueContainer;
}
public HighAvailableAgentPool() {
this.setHighAvailablePool(new ArrayList<Agent>());
this.agentStatusOfPreviousBeatMap = new HashMap<String, ServerStatusModel>();
this.setMaxLoadOfHAPool((long) 0);
}
public Long getMaxLoadOfHAPool() {
return maxLoadOfHAPool;
}
private void setMaxLoadOfHAPool(Long maxLoadOfHAPool) {
this.maxLoadOfHAPool = maxLoadOfHAPool;
}
@Scheduled(cron = "0 */1 * * * *")
public void timerTask() {
synchronized (this.highAvailablePool) {
_heartBeatsAndUpdateHAPool();
}
System.out.println("hah");
}
private void _heartBeatsAndUpdateHAPool() {
this.highAvailablePool.removeAll(this.highAvailablePool);
List<Agent> agents = this.agentService.loadAgentPoolFromDB();
ServerStatusModel model = new ServerStatusModel();
for (int i = 0; i < agents.size(); i++) {
model = queryAgentStatus(agents.get(i));
if (model == null) {
_doForBreakDown(model, agents.get(i).getHostName());
continue;
}
_doForHealth(model, agents.get(i));
}
}
public ServerStatusModel queryAgentStatus(Agent agent) {
return this.agentStateService.askLiving(agent.getHostName(),
agent.getPort());
}
private void _doForBreakDown(ServerStatusModel statusModel, String hostName) {
// TODO:should add some handle to deal with the break down.
// at first, we should find its running task by find the
// count of unfinished count from the
// agentStatusOfPreviousBeatMap, and do it on its
// secondary node, but now i only let it do it in a way of
// rerun it with another agent.
List<UUID> agentUnfinishedRunIdsList = _queryAgentUnfinishedTest(
statusModel, hostName);
this.agentService.updateAgentStatus(
AgentService.AGENT_STATUS_BreakDown, hostName);
for (int i = 0; i < agentUnfinishedRunIdsList.size(); i++) {
HostNameLoadScriptId hostNameLoadScriptId = this.taskQueueContainer
.queryHostNameLoadScriptFromTestPlanContext(agentUnfinishedRunIdsList
.get(i));
if (hostNameLoadScriptId == null) {
return;
}
Agent backAgent = this.getAgentWithEnoughLoad(hostNameLoadScriptId
.getLoad());
}
}
private Agent getAgentWithEnoughLoad(int load) {
for (Agent agent : this.highAvailablePool) {
if (agent.getCurrentStatus() != AgentService.AGENT_STATUS_Idel
|| agent.getRemainLoad() < load) {
continue;
}
return agent;
}
return null;
}
private void _doForHealth(ServerStatusModel newModel, Agent agent) {
_arrageUnfinishedTest(newModel, agent.getHostName());
_arrangeFinishedTest(newModel, agent.getHostName());
this.setMaxLoadOfHAPool((long) agent.getRemainLoad());
this.agentStatusOfPreviousBeatMap.put(agent.getHostName(), newModel);
this.highAvailablePool.add(agent);
}
private void _arrageUnfinishedTest(ServerStatusModel newModel,
String hostName) {
List<UUID> agentUnfinishedRunIds = _queryAgentUnfinishedTest(newModel,
hostName);
if (agentUnfinishedRunIds == null || agentUnfinishedRunIds.size() == 0) {
this.agentService.updateAgentStatus(AgentService.AGENT_STATUS_Idel,
hostName);
return;
}
this.agentService.updateAgentStatus(AgentService.AGENT_STATUS_InRun,
hostName);
}
private void _arrangeFinishedTest(ServerStatusModel newModel,
String hostName) {
List<UUID> agentFinishRunIds = _queryAgentNewFinishTest(newModel,
hostName);
for (int i = 0; i < agentFinishRunIds.size(); i++) {
HostNameLoadScriptId hostNameAndLoad = this.taskQueueContainer
.queryHostNameLoadScriptFromTestPlanContext(agentFinishRunIds
.get(i));
if (hostNameAndLoad == null) {
return;
}
this.agentService.backLoadToAgent(hostNameAndLoad.getHostName(),
hostNameAndLoad.getLoad());
}
}
private List<UUID> _queryAgentUnfinishedTest(ServerStatusModel newModel,
String hostName) {
ServerStatusModel underRecoverModel = this.agentStatusOfPreviousBeatMap
.get(hostName);
if (underRecoverModel == null) {
return null;
}
return underRecoverModel.getRunningTests();
}
private List<UUID> _queryAgentNewFinishTest(ServerStatusModel newModel,
String hostName) {
ServerStatusModel previousModel = this.agentStatusOfPreviousBeatMap
.get(hostName);
List<UUID> previousFinishTestList = new ArrayList<UUID>();
List<UUID> currentFinishTestList = new ArrayList<UUID>();
List<UUID> result = new ArrayList<UUID>();
if (previousModel == null) {
return newModel.getFinishedTests();
}
previousFinishTestList = previousModel.getFinishedTests();
currentFinishTestList = newModel.getFinishedTests();
for (int i = 0; i < currentFinishTestList.size(); i++) {
if (previousFinishTestList.contains(currentFinishTestList.get(i))) {
continue;
}
result.add(currentFinishTestList.get(i));
}
return result;
}
}

View File

@ -0,0 +1,199 @@
package org.bench4q.master.testPlan;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.bench4q.master.api.model.RunningScriptModel;
import org.bench4q.master.api.model.TestPlanModel;
import org.bench4q.master.communication.HttpRequester;
import org.bench4q.master.communication.agent.RunScenarioModel;
import org.bench4q.master.communication.agent.RunScenarioResultModel;
import org.bench4q.master.entity.db.Agent;
import org.bench4q.master.service.AgentService;
import org.bench4q.master.service.ScriptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class LoadBallancer {
private ScriptService scriptService;
private AgentService agentService;
private HighAvailableAgentPool highAvailableAgentPool;
private TaskQueueContainer taskQueueContainer;
private boolean monopolizeByUserSet = true;
@Autowired
public void setScriptService(ScriptService scriptService) {
this.scriptService = scriptService;
}
private boolean isMonopolizeByUserSet() {
return monopolizeByUserSet;
}
public void setMonopolizeByUserSet(boolean monopolize) {
this.monopolizeByUserSet = monopolize;
}
private AgentService getAgentService() {
return agentService;
}
@Autowired
public void setAgentService(AgentService agentService) {
this.agentService = agentService;
}
@Autowired
public void setHttpRequester(HttpRequester httpRequester) {
}
@Autowired
public void setHighAvailableAgentPool(
HighAvailableAgentPool highAvailableAgentPool) {
this.highAvailableAgentPool = highAvailableAgentPool;
}
@Autowired
public void setTaskQueueContainer(TaskQueueContainer taskQueueContainer) {
this.taskQueueContainer = taskQueueContainer;
}
private int getTotalLoad(TestPlanModel testPlanModel) {
Iterator<RunningScriptModel> iterator = testPlanModel
.getRunnningScriptModels().iterator();
int result = 0;
RunningScriptModel runningScriptModel = null;
while (iterator.hasNext()) {
runningScriptModel = iterator.next();
result += runningScriptModel.getRequireLoad();
}
return result;
}
public List<RunningScriptModel> generateLoadForTestPlan(
TestPlanModel testPlanModel, UUID testPlanId) {
List<RunningScriptModel> result = new ArrayList<RunningScriptModel>();
synchronized (this.highAvailableAgentPool.getHighAvailablePool()) {
if (this.getTotalLoad(testPlanModel) >= this.highAvailableAgentPool
.getMaxLoadOfHAPool()) {
return null;
}
Iterator<RunningScriptModel> iterator = testPlanModel
.getRunnningScriptModels().iterator();
while (iterator.hasNext()) {
RunningScriptModel sModel = iterator.next();
result.add(this._generateLoadForScript(sModel.getScriptId(),
sModel.getRequireLoad(), testPlanId));
}
return result;
}
}
private RunningScriptModel _generateLoadForScript(int scriptId,
int requireLoad, UUID testPlanId) {
RunScenarioModel runScenarioModel = this.scriptService
.getRunSceniroModelByScriptId(scriptId);
if (runScenarioModel == null) {
return null;
}
try {
RunningScriptModel result = this._runAgentsWithScenario(
runScenarioModel, requireLoad, scriptId, testPlanId);
result.setRequireLoad(requireLoad);
return result;
} catch (JAXBException e) {
e.printStackTrace();
return null;
}
}
private RunningScriptModel _runAgentsWithScenario(
RunScenarioModel runScenarioModel, int requireLoad, int scriptId,
UUID testPlanId) throws JAXBException {
Iterator<Agent> iterator;
Agent agent;
RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel();
List<UUID> runIdList = new ArrayList<UUID>();
int min;
for (iterator = this.highAvailableAgentPool.getHighAvailablePool()
.iterator(); iterator.hasNext() && requireLoad > 0;) {
agent = iterator.next();
if (this.highAvailableAgentPool.queryAgentStatus(agent) == null) {
continue;
}
if (_isMonopolized(agent)) {
continue;
}
min = _getMin(requireLoad, agent.getRemainLoad());
runScenarioModel.setPoolSize(min);
runScenarioModel.setTotalCount(min);
this.getAgentService().getLoadFromAgent(agent.getHostName(), min);
runScenarioResultModel = this.getAgentService().run(agent,
this._marshalRunScenarioModelToString(runScenarioModel));
// runScenarioResultModel = this._sendScriptContentToAgent(
// agent.getHostName(), agent.getPort(),
// this._marshalRunScenarioModelToString(runScenarioModel));
this._addToRunIdHostLoadMap(
testPlanId,
runScenarioResultModel.getRunId(),
new HostNameLoadScriptId(agent.getHostName(), min, scriptId));
runIdList.add(runScenarioResultModel.getRunId());
requireLoad -= min;
}
if (requireLoad > 0) {
return _buildRunningScriptModel(null, -1);
}
return _buildRunningScriptModel(runIdList, scriptId);
}
private void _addToRunIdHostLoadMap(UUID testPlanId, UUID agentRunId,
HostNameLoadScriptId hostNameAndLoad) {
TestPlanContext testPlanContext = this.taskQueueContainer
.queryTestPlanContext(testPlanId);
testPlanContext.addToRunIdHostLoadMap(agentRunId, hostNameAndLoad);
}
private boolean _isMonopolized(Agent agent) {
return agent.getRemainLoad() < agent.getMaxLoad()
&& this.isMonopolizeByUserSet();
}
private int _getMin(int requireLoad, int remainLoadByStart) {
return remainLoadByStart >= requireLoad ? requireLoad
: remainLoadByStart;
}
private String _marshalRunScenarioModelToString(
RunScenarioModel runScenarioModel) throws JAXBException {
Marshaller marshaller;
marshaller = JAXBContext.newInstance(runScenarioModel.getClass())
.createMarshaller();
StringWriter stringWriter = new StringWriter();
marshaller.marshal(runScenarioModel, stringWriter);
return stringWriter.toString();
}
private RunningScriptModel _buildRunningScriptModel(List<UUID> agentRunIds,
int scriptId) {
RunningScriptModel result = new RunningScriptModel();
result.setAgentRunIds(agentRunIds);
result.setScriptId(scriptId);
return result;
}
}

View File

@ -0,0 +1,68 @@
package org.bench4q.master.testPlan;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class RunningAgentInfo {
private Map<UUID, HostNameLoadScriptId> runIdHostLoadMap = new HashMap<UUID, HostNameLoadScriptId>();
public Map<UUID, HostNameLoadScriptId> getRunIdHostLoadMap() {
return runIdHostLoadMap;
}
public void setRunIdHostLoadMap(
Map<UUID, HostNameLoadScriptId> runIdAgentMap) {
this.runIdHostLoadMap = runIdAgentMap;
}
public boolean addToRunIdHostLoadMap(UUID uuid,
HostNameLoadScriptId hostNameAndLoad) {
return this.runIdHostLoadMap.put(uuid, hostNameAndLoad) != null;
}
public boolean removeFromRunIdHostLoadMap(UUID uuid) {
return this.runIdHostLoadMap.remove(uuid) != null;
}
public HostNameLoadScriptId queryHostNameLoadScriptId(UUID agentRunId) {
return this.runIdHostLoadMap.get(agentRunId);
}
}
class HostNameLoadScriptId {
private String hostName;
private int load;
private int scriptId;
public HostNameLoadScriptId(String hostName, int load, int ScriptId) {
this.setHostName(hostName);
this.setLoad(load);
this.setScriptId(scriptId);
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
public int getLoad() {
return load;
}
public void setLoad(int load) {
this.load = load;
}
public int getScriptId() {
return scriptId;
}
public void setScriptId(int scriptId) {
this.scriptId = scriptId;
}
}

View File

@ -0,0 +1,63 @@
package org.bench4q.master.testPlan;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import org.springframework.stereotype.Component;
@Component
public class TaskQueueContainer {
private Map<UUID, TestPlanContext> taskQueue = new HashMap<UUID, TestPlanContext>();
public Map<UUID, TestPlanContext> getTaskQueue() {
return taskQueue;
}
public void setTaskQueue(Map<UUID, TestPlanContext> taskQueue) {
this.taskQueue = taskQueue;
}
public TestPlanContext queryTestPlanContext(UUID testPlanId) {
return this.taskQueue.get(testPlanId);
}
public TestPlanContext addATask(UUID testPlanId,
TestPlanContext testPlanContext) {
return this.taskQueue.put(testPlanId, testPlanContext);
}
public HostNameLoadScriptId queryHostNameLoadScriptFromTestPlanContext(
UUID agentRunId) {
Iterator<TestPlanContext> iterator = this.taskQueue.values().iterator();
while (iterator.hasNext()) {
TestPlanContext testPlanContext = iterator.next();
HostNameLoadScriptId result = testPlanContext
.queryHostNameAndLoadFromRunningAgentInfo(agentRunId);
if (result == null) {
continue;
}
return result;
}
return null;
}
public HostNameLoadScriptId queryHostNameAndLoad(UUID testPlanId, UUID runId) {
TestPlanContext testPlanContext = queryTestPlanContext(testPlanId);
if (testPlanContext == null) {
return null;
}
HostNameLoadScriptId hostNameAndLoad = testPlanContext
.queryHostNameAndLoadFromRunningAgentInfo(runId);
return hostNameAndLoad;
}
public RunningAgentInfo queryRunningAgentInfo(UUID testPlanId) {
TestPlanContext testPlanContext = this.taskQueue.get(testPlanId);
if (testPlanContext == null) {
return null;
}
return testPlanContext.getRunningAgentInfo();
}
}

View File

@ -0,0 +1,63 @@
package org.bench4q.master.testPlan;
import java.util.List;
import java.util.UUID;
import org.bench4q.master.api.model.TestPlanResultModel;
import org.bench4q.master.api.model.RunningScriptModel;
import org.bench4q.master.api.model.TestPlanModel;
import org.springframework.beans.factory.annotation.Autowired;
public class TestPlanContext {
private TestPlanModel testPlanModel;
private RunningAgentInfo runningAgentInfo;
private TestPlanResultModel resultModel;
public TestPlanModel getTestPlanModel() {
return testPlanModel;
}
public void setTestPlanModel(TestPlanModel testPlanModel) {
this.testPlanModel = testPlanModel;
}
public RunningAgentInfo getRunningAgentInfo() {
return runningAgentInfo;
}
private void setRunningAgentInfo(RunningAgentInfo runningAgentInfo) {
this.runningAgentInfo = runningAgentInfo;
}
public TestPlanResultModel getResultModel() {
return resultModel;
}
@Autowired
public void setResultModel(TestPlanResultModel resultModel) {
this.resultModel = resultModel;
}
public TestPlanContext() {
this.setRunningAgentInfo(new RunningAgentInfo());
this.setTestPlanModel(new TestPlanModel());
}
public void addRunningScriptModelsToResult(List<RunningScriptModel> list) {
if (list == null) {
return;
}
this.getResultModel().getRunningScriptModels().addAll(list);
}
public HostNameLoadScriptId queryHostNameAndLoadFromRunningAgentInfo(
UUID agentRunId) {
return this.getRunningAgentInfo().getRunIdHostLoadMap().get(agentRunId);
}
public void addToRunIdHostLoadMap(UUID agentRunId,
HostNameLoadScriptId hostNameAndLoad) {
this.getRunningAgentInfo().addToRunIdHostLoadMap(agentRunId,
hostNameAndLoad);
}
}

View File

@ -0,0 +1,260 @@
package org.bench4q.master.testPlan;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.bench4q.master.api.model.AgentBriefModel;
import org.bench4q.master.api.model.AgentDetailModel;
import org.bench4q.master.api.model.TestPlanConfig;
import org.bench4q.master.api.model.TestPlanResultModel;
import org.bench4q.master.api.model.RunningScriptModel;
import org.bench4q.master.api.model.TestPlanModel;
import org.bench4q.master.communication.AgentStateService;
import org.bench4q.master.communication.HttpRequester;
import org.bench4q.master.communication.HttpRequester.HttpResponse;
import org.bench4q.master.communication.agent.TestBriefStatusModel;
import org.bench4q.master.communication.agent.TestDetailStatusModel;
import org.bench4q.master.entity.db.User;
import org.bench4q.master.service.AgentService;
import org.bench4q.master.service.TestPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TestPlanRunner {
private AgentService agentService;
private TestPlanService testPlanService;
private HttpRequester httpRequester;
private LoadBallancer loadBallancer;
private TaskQueueContainer taskQueueContainer;
private final int POOL_SIZE = 100;
public static final long TimeUnit = 1000;
@Autowired
public void setAgentService(AgentService agentService) {
this.agentService = agentService;
}
@Autowired
public void setAgentStateService(AgentStateService agentStateService) {
}
@Autowired
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
@Autowired
public void setLoadBallancer(LoadBallancer loadBallancer) {
this.loadBallancer = loadBallancer;
}
@Autowired
public void setTaskQueueContainer(TaskQueueContainer taskQueueContainer) {
this.taskQueueContainer = taskQueueContainer;
}
@Autowired
public void setTestPlanService(TestPlanService testPlanService) {
this.testPlanService = testPlanService;
}
public Map<UUID, TestPlanContext> get_tasks() {
return this.taskQueueContainer.getTaskQueue();
}
public TestPlanResultModel queryTestPlanResultModel(UUID testPlanId) {
TestPlanContext context = this.taskQueueContainer.getTaskQueue().get(
testPlanId);
return context == null ? null : context.getResultModel();
}
public AgentBriefModel getBriefStatusFromAgent(UUID testPlanId, UUID runId) {
AgentBriefModel result = new AgentBriefModel();
TestBriefStatusModel briefStatusModel = new TestBriefStatusModel();
try {
HostNameLoadScriptId hostNameAndLoad = this.taskQueueContainer
.queryHostNameAndLoad(testPlanId, runId);
if (hostNameAndLoad == null) {
return null;
}
HttpResponse httpResponse = this.httpRequester.sendGet(
hostNameAndLoad.getHostName() + ":" + AgentService.PORT
+ "/test/brief/" + runId, null, null);
briefStatusModel = this._extractTestBriefStatusModel(httpResponse
.getContent());
result = this._makeAgentBriefModel(briefStatusModel);
return result;
} catch (IOException e) {
e.printStackTrace();
return result;
} catch (JAXBException e) {
e.printStackTrace();
return result;
}
}
private TestBriefStatusModel _extractTestBriefStatusModel(String content)
throws JAXBException {
TestBriefStatusModel resultModel = new TestBriefStatusModel();
Unmarshaller ummarshaller = JAXBContext.newInstance(
resultModel.getClass()).createUnmarshaller();
resultModel = (TestBriefStatusModel) ummarshaller
.unmarshal(new ByteArrayInputStream(content.getBytes()));
return resultModel;
}
private AgentBriefModel _makeAgentBriefModel(
TestBriefStatusModel briefStatusModel) {
AgentBriefModel result = new AgentBriefModel();
result.setTestStatusModel(briefStatusModel);
result.setFinish(briefStatusModel.getFinishedCount() == briefStatusModel
.getTotalCount());
return result;
}
public UUID runTestPlanWithModel(final TestPlanModel testPlanModel,
User user) {
ExecutorService executorService = Executors
.newFixedThreadPool(this.POOL_SIZE);
final UUID testPlanId = UUID.randomUUID();
final TestPlanContext testPlanContext = new TestPlanContext();
TestPlanResultModel resultModel = new TestPlanResultModel();
resultModel.setRunningScriptModels(new ArrayList<RunningScriptModel>());
resultModel.setTestPlanId(testPlanId);
testPlanContext.setTestPlanModel(testPlanModel);
testPlanContext.setResultModel(resultModel);
if (!this.testPlanService.saveTestPlanToDB(testPlanModel, user)) {
return null;
}
this.taskQueueContainer.addATask(testPlanId, testPlanContext);
Runnable runnable = new Runnable() {
public void run() {
testPlanContext.addRunningScriptModelsToResult((_doRunTestPlan(
testPlanModel, testPlanId)));
}
};
executorService.execute(runnable);
executorService.shutdown();
return testPlanId;
}
private List<RunningScriptModel> _doRunTestPlan(
TestPlanModel testPlanModel, UUID testPlanId) {
List<RunningScriptModel> result = new ArrayList<RunningScriptModel>();
if (!schedulePlanConfig(testPlanModel, testPlanId)) {
return null;
}
result = this.loadBallancer.generateLoadForTestPlan(testPlanModel,
testPlanId);
return result;
}
private boolean schedulePlanConfig(TestPlanModel testPlanModel,
UUID testPlanId) {
TestPlanConfig testPlanConfig = testPlanModel.getConfig();
if (testPlanConfig == null) {
return false;
}
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// TODO: let the agent do startSaveDetail
System.out.println("warm up over and start to execute!");
}
}, testPlanConfig.getWarmUp() * TimeUnit);
ExecutionOverTask executionOverTask = new ExecutionOverTask();
executionOverTask.setRunningAgentInfo(this.taskQueueContainer
.queryRunningAgentInfo(testPlanId));
timer.schedule(executionOverTask,
(testPlanConfig.getWarmUp() + testPlanConfig.getExecuteRange())
* TimeUnit);
timer.schedule(
new TimerTask() {
@Override
public void run() {
System.out.println("cool down over!");
}
},
(testPlanConfig.getWarmUp() + testPlanConfig.getExecuteRange() + testPlanConfig
.getCoolDown()) * TimeUnit);
return true;
}
public AgentDetailModel getDetailStatusOfAgent(UUID testPlanId,
UUID agentRunId) {
AgentDetailModel result = new AgentDetailModel();
TestDetailStatusModel detailStatusModel = new TestDetailStatusModel();
try {
HostNameLoadScriptId hostNameAndLoad = this.taskQueueContainer
.queryHostNameAndLoad(testPlanId, agentRunId);
if (hostNameAndLoad == null) {
return null;
}
HttpResponse httpResponse = this.httpRequester.sendGet(
hostNameAndLoad.getHostName() + ":" + AgentService.PORT
+ "/test/detail/" + agentRunId, null, null);
detailStatusModel = this.extractDetailStatusModel(httpResponse
.getContent());
result = this.buildAgentDetailModel(detailStatusModel);
if (result.isFinish()) {
this.agentService.backLoadToAgent(
hostNameAndLoad.getHostName(),
hostNameAndLoad.getLoad());
}
return result;
} catch (IOException e) {
e.printStackTrace();
return result;
} catch (JAXBException e) {
e.printStackTrace();
return result;
}
}
private TestDetailStatusModel extractDetailStatusModel(String content)
throws JAXBException {
TestDetailStatusModel result = new TestDetailStatusModel();
Unmarshaller unmarshaller = JAXBContext.newInstance(result.getClass())
.createUnmarshaller();
result = (TestDetailStatusModel) unmarshaller
.unmarshal(new ByteArrayInputStream(content.getBytes()));
return result;
}
private AgentDetailModel buildAgentDetailModel(
TestDetailStatusModel detailStatusModel) {
AgentDetailModel result = new AgentDetailModel();
result.setTestStatusModel(detailStatusModel);
result.setFinish(detailStatusModel.getFinishedCount() == detailStatusModel
.getTotalCount());
return result;
}
}

View File

@ -0,0 +1,13 @@
<?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 />
</beans>

View File

@ -0,0 +1,30 @@
<?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>
<mapping class="org.bench4q.master.entity.db.User" />
<mapping class="org.bench4q.master.entity.db.Script" />
<mapping class="org.bench4q.master.entity.db.Behavior" />
<mapping class="org.bench4q.master.entity.db.PlanConfig" />
<mapping class="org.bench4q.master.entity.db.Sample" />
<mapping class="org.bench4q.master.entity.db.Timer" />
<mapping class="org.bench4q.master.entity.db.Agent" />
<mapping class="org.bench4q.master.entity.db.Port" />
<mapping class="org.bench4q.master.entity.db.TestPlan" />
<mapping class="org.bench4q.master.entity.db.Plugin" />
<mapping class="org.bench4q.master.entity.db.TestPlanScript" />
</session-factory>
</hibernate-configuration>

View File

@ -0,0 +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
#generator.isac.timer.random.delta=10

Some files were not shown because too many files have changed in this diff Show More