This commit is contained in:
coderfengyun 2014-09-02 10:41:46 +08:00
parent 6c19a07c61
commit 2b3f97a605
8 changed files with 1105 additions and 1105 deletions

View File

@ -1,155 +1,155 @@
package org.bench4q.agent.scenario.engine;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;
import org.apache.log4j.Logger;
import org.bench4q.agent.datacollector.DataCollector;
import org.bench4q.agent.datacollector.impl.ScenarioResultCollector;
import org.bench4q.agent.plugin.PluginManager;
import org.bench4q.agent.scenario.Scenario;
public class ScenarioContext implements Observer {
private static final long keepAliveTime = 10;
private final UUID testId;
private final Date startDate;
private Date endDate;
private final ThreadPoolExecutor executor;
private Scenario scenario;
private boolean finished;
private final DataCollector dataCollector;
private final PluginManager pluginManager;
public ScenarioContext(UUID testId, Date startDate,
ThreadPoolExecutor executor, DataCollector dataCollector, PluginManager pluginManager) {
this.testId = testId;
this.startDate = startDate;
this.executor = executor;
this.dataCollector = dataCollector;
this.pluginManager = pluginManager;
}
public UUID getTestId() {
return testId;
}
public Date getStartDate() {
return startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public ThreadPoolExecutor getExecutor() {
return executor;
}
public Scenario getScenario() {
return scenario;
}
public void setScenario(Scenario scenario) {
this.scenario = scenario;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public DataCollector getDataStatistics() {
return dataCollector;
}
private PluginManager getPluginManager() {
return pluginManager;
}
public static ScenarioContext buildScenarioContext(UUID testId,
final Scenario scenario, int poolSize, PluginManager pluginManager) {
ScenarioContext scenarioContext = buildScenarioContextWithoutScenario(
testId, poolSize, pluginManager);
scenarioContext.setScenario(scenario);
scenario.getSchedule().addObserver(scenarioContext);
return scenarioContext;
}
public static ScenarioContext buildScenarioContextWithoutScenario(
UUID testId, int poolSize, PluginManager pluginManager) {
final ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(
poolSize);
ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize,
poolSize, keepAliveTime, TimeUnit.MINUTES, workQueue,
new DiscardPolicy());
ScenarioContext scenarioContext = new ScenarioContext(testId, new Date(
System.currentTimeMillis()), executor,
new ScenarioResultCollector(testId), pluginManager);
return scenarioContext;
}
public ScenarioContext addScenrio(final Scenario scenario, final long realStartTime) {
ScenarioContext result = new ScenarioContext(this.testId, new Date(realStartTime), executor, this.dataCollector, pluginManager);
result.setEndDate(new Date(scenario.getSchedule().getScheduleRange() + this.getStartDate().getTime()));
result.setFinished(this.isFinished());
result.setScenario(scenario);
return result;
}
/**
* Now, I tolerate that if the requiredLoad <
* this.getExecutor.getCorePoolSize(), then the excess threads will be
* killed when its current task complete
*
* @param requiredLoad
*/
public void updatePopulation(int requiredLoad) {
this.getExecutor().setCorePoolSize(requiredLoad);
this.getExecutor().setMaximumPoolSize(requiredLoad);
}
public void addTask() {
if (this.isFinished()) {
return;
}
this.getExecutor().execute(new VUser(this, 1, getPluginManager()));
Logger.getLogger(this.getClass()).info(
this.getExecutor().getActiveCount());
}
public void initTasks(int currentLoad) {
this.updatePopulation(currentLoad);
for (int i = 0; i < currentLoad; i++) {
addTask();
}
}
@Override
public void update(Observable o, Object arg) {
Schedule schedule = (Schedule) o;
if (schedule.hasReachEnd()) {
stop();
} else {
this.updatePopulation((Integer) arg);
}
}
public void stop() {
this.setFinished(true);
this.setEndDate(new Date());
this.getExecutor().shutdownNow();
}
}
package org.bench4q.agent.scenario.engine;
import java.util.Date;
import java.util.Observable;
import java.util.Observer;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy;
import org.apache.log4j.Logger;
import org.bench4q.agent.datacollector.DataCollector;
import org.bench4q.agent.datacollector.impl.ScenarioResultCollector;
import org.bench4q.agent.plugin.PluginManager;
import org.bench4q.agent.scenario.Scenario;
public class ScenarioContext implements Observer {
private static final long keepAliveTime = 10;
private final UUID testId;
private final Date startDate;
private Date endDate;
private final ThreadPoolExecutor executor;
private Scenario scenario;
private boolean finished;
private final DataCollector dataCollector;
private final PluginManager pluginManager;
public ScenarioContext(UUID testId, Date startDate,
ThreadPoolExecutor executor, DataCollector dataCollector, PluginManager pluginManager) {
this.testId = testId;
this.startDate = startDate;
this.executor = executor;
this.dataCollector = dataCollector;
this.pluginManager = pluginManager;
}
public UUID getTestId() {
return testId;
}
public Date getStartDate() {
return startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public ThreadPoolExecutor getExecutor() {
return executor;
}
public Scenario getScenario() {
return scenario;
}
public void setScenario(Scenario scenario) {
this.scenario = scenario;
}
public boolean isFinished() {
return finished;
}
public void setFinished(boolean finished) {
this.finished = finished;
}
public DataCollector getDataStatistics() {
return dataCollector;
}
private PluginManager getPluginManager() {
return pluginManager;
}
public static ScenarioContext buildScenarioContext(UUID testId,
final Scenario scenario, int poolSize, PluginManager pluginManager) {
ScenarioContext scenarioContext = buildScenarioContextWithoutScenario(
testId, poolSize, pluginManager);
scenarioContext.setScenario(scenario);
scenario.getSchedule().addObserver(scenarioContext);
return scenarioContext;
}
public static ScenarioContext buildScenarioContextWithoutScenario(
UUID testId, int poolSize, PluginManager pluginManager) {
final ArrayBlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<Runnable>(
poolSize);
ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize,
poolSize, keepAliveTime, TimeUnit.MINUTES, workQueue,
new DiscardPolicy());
ScenarioContext scenarioContext = new ScenarioContext(testId, new Date(
System.currentTimeMillis()), executor,
new ScenarioResultCollector(testId), pluginManager);
return scenarioContext;
}
public ScenarioContext addScenrio(final Scenario scenario, final long realStartTime) {
ScenarioContext result = new ScenarioContext(this.testId, new Date(realStartTime), executor, this.dataCollector, pluginManager);
result.setEndDate(new Date(scenario.getSchedule().getScheduleRange() + this.getStartDate().getTime()));
result.setFinished(this.isFinished());
result.setScenario(scenario);
return result;
}
/**
* Now, I tolerate that if the requiredLoad <
* this.getExecutor.getCorePoolSize(), then the excess threads will be
* killed when its current task complete
*
* @param requiredLoad
*/
public void updatePopulation(int requiredLoad) {
this.getExecutor().setCorePoolSize(requiredLoad);
this.getExecutor().setMaximumPoolSize(requiredLoad);
}
public void addTask() {
if (this.isFinished()) {
return;
}
this.getExecutor().execute(new VUser(this, 1, getPluginManager()));
Logger.getLogger(this.getClass()).info(
this.getExecutor().getActiveCount());
}
public void initTasks(int currentLoad) {
this.updatePopulation(currentLoad);
for (int i = 0; i < currentLoad; i++) {
addTask();
}
}
@Override
public void update(Observable o, Object arg) {
Schedule schedule = (Schedule) o;
if (schedule.hasReachEnd()) {
stop();
} else {
this.updatePopulation((Integer) arg);
}
}
public void stop() {
this.setFinished(true);
this.setEndDate(new Date());
this.getExecutor().shutdownNow();
}
}

View File

@ -1,100 +1,100 @@
package org.bench4q.agent.scenario.engine;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.bench4q.agent.plugin.PluginManager;
import org.bench4q.agent.scenario.Scenario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ScenarioEngine implements Observer {
private Map<UUID, ScenarioContext> runningTests;
private final Logger logger = Logger.getLogger(ScenarioEngine.class);
private PluginManager pluginManager;
public ScenarioEngine() {
this.setRunningTests(new HashMap<UUID, ScenarioContext>());
}
public Map<UUID, ScenarioContext> getRunningTests() {
return runningTests;
}
private void setRunningTests(Map<UUID, ScenarioContext> runningTests) {
this.runningTests = runningTests;
}
private PluginManager getPluginManager() {
return pluginManager;
}
@Autowired
private void setPluginManager(PluginManager pluginManager) {
this.pluginManager = pluginManager;
}
public void addRunningTestWithoutScenario(UUID runId, int poolSize) {
try {
final ScenarioContext scenarioContext = ScenarioContext
.buildScenarioContextWithoutScenario(runId, poolSize,
getPluginManager());
this.getRunningTests().put(runId, scenarioContext);
} catch (Exception e) {
e.printStackTrace();
}
}
public void submitScenario(final UUID runId, final Scenario scenario, final long realStartTime) {
try {
ScenarioContext old = this.getRunningTests().get(runId);
this.getRunningTests().put(runId, old.addScenrio(scenario, realStartTime));
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean runWith(UUID runId) {
if (!this.getRunningTests().containsKey(runId)) {
return false;
}
final ScenarioContext context = this.getRunningTests().get(runId);
return runWith(context);
}
private boolean runWith(final ScenarioContext scenarioContext) {
if (scenarioContext == null) {
logger.error("The context required is null");
return false;
}
try {
int currentLoad = scenarioContext
.getScenario()
.getSchedule()
.loadFor(
System.currentTimeMillis()
- scenarioContext.getStartDate().getTime());
scenarioContext.initTasks(currentLoad);
new Supervisor(scenarioContext).start();
return true;
} catch (Exception e) {
this.logger.info(e, e);
return false;
}
}
@Override
public void update(Observable o, Object arg) {
if (!(o instanceof Supervisor)) {
return;
}
UUID testId = (UUID) arg;
this.getRunningTests().remove(testId);
}
}
package org.bench4q.agent.scenario.engine;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.bench4q.agent.plugin.PluginManager;
import org.bench4q.agent.scenario.Scenario;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ScenarioEngine implements Observer {
private Map<UUID, ScenarioContext> runningTests;
private final Logger logger = Logger.getLogger(ScenarioEngine.class);
private PluginManager pluginManager;
public ScenarioEngine() {
this.setRunningTests(new HashMap<UUID, ScenarioContext>());
}
public Map<UUID, ScenarioContext> getRunningTests() {
return runningTests;
}
private void setRunningTests(Map<UUID, ScenarioContext> runningTests) {
this.runningTests = runningTests;
}
private PluginManager getPluginManager() {
return pluginManager;
}
@Autowired
private void setPluginManager(PluginManager pluginManager) {
this.pluginManager = pluginManager;
}
public void addRunningTestWithoutScenario(UUID runId, int poolSize) {
try {
final ScenarioContext scenarioContext = ScenarioContext
.buildScenarioContextWithoutScenario(runId, poolSize,
getPluginManager());
this.getRunningTests().put(runId, scenarioContext);
} catch (Exception e) {
e.printStackTrace();
}
}
public void submitScenario(final UUID runId, final Scenario scenario, final long realStartTime) {
try {
ScenarioContext old = this.getRunningTests().get(runId);
this.getRunningTests().put(runId, old.addScenrio(scenario, realStartTime));
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean runWith(UUID runId) {
if (!this.getRunningTests().containsKey(runId)) {
return false;
}
final ScenarioContext context = this.getRunningTests().get(runId);
return runWith(context);
}
private boolean runWith(final ScenarioContext scenarioContext) {
if (scenarioContext == null) {
logger.error("The context required is null");
return false;
}
try {
int currentLoad = scenarioContext
.getScenario()
.getSchedule()
.loadFor(
System.currentTimeMillis()
- scenarioContext.getStartDate().getTime());
scenarioContext.initTasks(currentLoad);
new Supervisor(scenarioContext).start();
return true;
} catch (Exception e) {
this.logger.info(e, e);
return false;
}
}
@Override
public void update(Observable o, Object arg) {
if (!(o instanceof Supervisor)) {
return;
}
UUID testId = (UUID) arg;
this.getRunningTests().remove(testId);
}
}

View File

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

View File

@ -1,29 +1,29 @@
package org.bench4q.recorder.httpcapture;
import java.net.HttpURLConnection;
public class ResponseModel {
private byte[] response;
private HttpURLConnection conn;
public byte[] getResponse() {
return response;
}
public void setResponse(byte[] response) {
this.response = response;
}
public ResponseModel(byte[] response, HttpURLConnection conn) {
this.setConn(conn);
this.response = response;
}
public HttpURLConnection getConn() {
return conn;
}
public void setConn(HttpURLConnection conn) {
this.conn = conn;
}
}
package org.bench4q.recorder.httpcapture;
import java.net.HttpURLConnection;
public class ResponseModel {
private byte[] response;
private HttpURLConnection conn;
public byte[] getResponse() {
return response;
}
public void setResponse(byte[] response) {
this.response = response;
}
public ResponseModel(byte[] response, HttpURLConnection conn) {
this.setConn(conn);
this.response = response;
}
public HttpURLConnection getConn() {
return conn;
}
public void setConn(HttpURLConnection conn) {
this.conn = conn;
}
}

View File

@ -1,25 +1,25 @@
package org.bench4q.recorder.httpcapture.generator;
import org.apache.log4j.Logger;
public class ContentEncoder {
protected Logger logger = Logger.getLogger(ContentEncoder.class);
protected ContentEncoder() {
}
public static ContentEncoder createEncoder(String encodeType) {
if (encodeType == null) {
return new ContentEncoder();
}
if (encodeType.equalsIgnoreCase("gzip")) {
return new GzipEncoder();
} else {
return new ContentEncoder();
}
}
public byte[] encoderContent(byte[] content){
return content;
}
}
package org.bench4q.recorder.httpcapture.generator;
import org.apache.log4j.Logger;
public class ContentEncoder {
protected Logger logger = Logger.getLogger(ContentEncoder.class);
protected ContentEncoder() {
}
public static ContentEncoder createEncoder(String encodeType) {
if (encodeType == null) {
return new ContentEncoder();
}
if (encodeType.equalsIgnoreCase("gzip")) {
return new GzipEncoder();
} else {
return new ContentEncoder();
}
}
public byte[] encoderContent(byte[] content){
return content;
}
}

View File

@ -1,25 +1,25 @@
package org.bench4q.recorder.httpcapture.generator;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GzipEncoder extends ContentEncoder{
public byte[] encoderContent(byte[] content){
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
gzipOutputStream.write(content, 0, content.length);
gzipOutputStream.finish();
gzipOutputStream.flush();
gzipOutputStream.close();
return outputStream.toByteArray();
} catch (IOException e) {
logger.error("decodeContent", e);
return null;
}
}
}
package org.bench4q.recorder.httpcapture.generator;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;
public class GzipEncoder extends ContentEncoder{
public byte[] encoderContent(byte[] content){
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputStream);
gzipOutputStream.write(content, 0, content.length);
gzipOutputStream.finish();
gzipOutputStream.flush();
gzipOutputStream.close();
return outputStream.toByteArray();
} catch (IOException e) {
logger.error("decodeContent", e);
return null;
}
}
}

View File

@ -1,271 +1,271 @@
package org.bench4q.web.masterMessager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.TestPlanDBModel;
import org.bench4q.share.models.master.TestPlanResponseModel;
import org.bench4q.share.models.master.TestPlanResultModel;
import org.bench4q.share.models.master.TestPlanScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
import org.springframework.stereotype.Component;
@Component
public class TestPlanMessager extends MasterMessager {
public TestPlanMessager() {
super(MasterAddressManamger.getMasterAddress() + "/testPlan");
}
public HttpResponse loadReport(String accessToken, String testPlanId) {
String url = this.getBaseUrl() + "/getTestPlanReport";
HttpResponse httpResponse = null;
try {
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanRunID", testPlanId);
httpResponse = this.getHttpRequester().sendGet(url, params,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
return null;
}
return httpResponse;
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
public TestPlanResultModel runTestPlan(String accessToken,
String testPlanXmlContent) {
String url = this.getBaseUrl() + "/run";
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendPostXml(url,
testPlanXmlContent, makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse))
return null;
return extractTestPlanResultModel(httpResponse);
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
public TestPlanResultModel getRunningTestInfo(String accessToken,
String testPlanId) {
String url = this.getBaseUrl() + "/getRunningInfo";
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanId", testPlanId);
return this.getTestPlanResultModelByPost(url, params, accessToken);
}
public TestPlanScriptBriefResultModel getScriptBriefResult(
String accessToken, String testPlanId, String scriptId,
String duationBegin) {
String url = this.getBaseUrl() + "/scriptBrief" + "/" + testPlanId
+ "/" + scriptId + "/" + duationBegin;
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return (TestPlanScriptBriefResultModel) MarshalHelper.unmarshal(
TestPlanScriptBriefResultModel.class,
httpResponse.getContent());
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
public ScriptBehaviorsBriefModel getScriptBehaviorsBriefResult(
String accessToken, String testPlanId, String scriptId) {
String url = this.getBaseUrl() + "/getBehaviorsBrief" + "/"
+ testPlanId + "/" + scriptId;
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse))
return null;
return (ScriptBehaviorsBriefModel) MarshalHelper.unmarshal(
ScriptBehaviorsBriefModel.class, httpResponse.getContent());
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
public TestPlanDBModel queryTestPlanById(String accessToken,
String testPlanRunId) {
String url = this.getBaseUrl() + "/queryTestPlan" + "/" + testPlanRunId;
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return (TestPlanDBModel) MarshalHelper.unmarshal(
TestPlanDBModel.class, httpResponse.getContent());
} catch (Exception e) {
handleException(httpResponse, e);
return null;
}
}
public TestPlanResponseModel deleteTestPlan(String accessToken,
String testPlanId) {
String url = this.getBaseUrl() + "/removeTestPlanFromPool";
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanId", testPlanId);
return getTestPlanResponseModel(url, params, accessToken);
}
public TestPlanResponseModel loadTestPlans(String accessToken) {
String url = this.getBaseUrl() + "/loadTestPlans";
return getTestPlanResponseModel(url, null, accessToken);
}
public HttpResponse getTestPlanReport(String accessToken,
String testPlanRunId) {
String url = this.getBaseUrl() + "/getTestPlanReport";
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanRunID", testPlanRunId);
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendPost(url, params,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse))
return null;
return httpResponse;
} catch (IOException e) {
this.handleException(httpResponse, e);
return null;
}
}
private TestPlanResponseModel getTestPlanResponseModel(String url,
Map<String, String> params, String accessToken) {
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendPost(url, params,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return extractTestPlanResponseModel(httpResponse);
} catch (Exception e) {
this.handleException(httpResponse, e);
return createFailTestPlanResponseModel();
}
}
private TestPlanResponseModel createFailTestPlanResponseModel() {
TestPlanResponseModel testPlanResponseModel = new TestPlanResponseModel();
testPlanResponseModel.setSuccess(false);
testPlanResponseModel.setFailCause("");
return testPlanResponseModel;
}
private TestPlanResultModel getTestPlanResultModelByPost(String url,
Map<String, String> params, String accessToken) {
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendPost(url, params,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse))
return null;
return extractTestPlanResultModel(httpResponse);
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
private TestPlanResponseModel extractTestPlanResponseModel(
HttpResponse httpResponse) throws JAXBException,
UnsupportedEncodingException {
return (TestPlanResponseModel) MarshalHelper.unmarshal(
TestPlanResponseModel.class, httpResponse.getContent());
}
private TestPlanResultModel extractTestPlanResultModel(
HttpResponse httpResponse) throws JAXBException,
UnsupportedEncodingException {
return (TestPlanResultModel) MarshalHelper.unmarshal(
TestPlanResultModel.class, httpResponse.getContent());
}
public ScriptBriefResultModel getLatestScriptBriefResult(
String accessToken, String testPlanId, String scriptId) {
String url = this.baseUrl + "/scriptBrief" + "/" + testPlanId + "/"
+ scriptId + "/latestResult";
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return (ScriptBriefResultModel) MarshalHelper.tryUnmarshal(
ScriptBriefResultModel.class, httpResponse.getContent());
} catch (Exception e) {
handleException(httpResponse, e);
return null;
}
}
public ScriptPagesBriefModel getScriptPageBriefModel(String accessToken,
String testPlanId, String scriptId) {
String url = this.baseUrl + "/pagesBrief" + "/" + testPlanId + "/"
+ scriptId;
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return (ScriptPagesBriefModel) MarshalHelper.unmarshal(
ScriptPagesBriefModel.class, httpResponse.getContent());
} catch (Exception e) {
handleException(httpResponse, e);
return null;
}
}
public TestPlanResponseModel stopTestPlan(String accessToken,
String testPlanRunId) {
String url = this.baseUrl + "/stop" + "/" + testPlanRunId;
return getTestPlanResponseModel(url, null, accessToken);
}
package org.bench4q.web.masterMessager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.bench4q.share.communication.HttpRequester.HttpResponse;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.TestPlanDBModel;
import org.bench4q.share.models.master.TestPlanResponseModel;
import org.bench4q.share.models.master.TestPlanResultModel;
import org.bench4q.share.models.master.TestPlanScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.share.models.master.statistics.ScriptBriefResultModel;
import org.bench4q.share.models.master.statistics.ScriptPagesBriefModel;
import org.springframework.stereotype.Component;
@Component
public class TestPlanMessager extends MasterMessager {
public TestPlanMessager() {
super(MasterAddressManamger.getMasterAddress() + "/testPlan");
}
public HttpResponse loadReport(String accessToken, String testPlanId) {
String url = this.getBaseUrl() + "/getTestPlanReport";
HttpResponse httpResponse = null;
try {
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanRunID", testPlanId);
httpResponse = this.getHttpRequester().sendGet(url, params,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
return null;
}
return httpResponse;
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
public TestPlanResultModel runTestPlan(String accessToken,
String testPlanXmlContent) {
String url = this.getBaseUrl() + "/run";
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendPostXml(url,
testPlanXmlContent, makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse))
return null;
return extractTestPlanResultModel(httpResponse);
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
public TestPlanResultModel getRunningTestInfo(String accessToken,
String testPlanId) {
String url = this.getBaseUrl() + "/getRunningInfo";
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanId", testPlanId);
return this.getTestPlanResultModelByPost(url, params, accessToken);
}
public TestPlanScriptBriefResultModel getScriptBriefResult(
String accessToken, String testPlanId, String scriptId,
String duationBegin) {
String url = this.getBaseUrl() + "/scriptBrief" + "/" + testPlanId
+ "/" + scriptId + "/" + duationBegin;
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return (TestPlanScriptBriefResultModel) MarshalHelper.unmarshal(
TestPlanScriptBriefResultModel.class,
httpResponse.getContent());
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
public ScriptBehaviorsBriefModel getScriptBehaviorsBriefResult(
String accessToken, String testPlanId, String scriptId) {
String url = this.getBaseUrl() + "/getBehaviorsBrief" + "/"
+ testPlanId + "/" + scriptId;
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse))
return null;
return (ScriptBehaviorsBriefModel) MarshalHelper.unmarshal(
ScriptBehaviorsBriefModel.class, httpResponse.getContent());
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
public TestPlanDBModel queryTestPlanById(String accessToken,
String testPlanRunId) {
String url = this.getBaseUrl() + "/queryTestPlan" + "/" + testPlanRunId;
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return (TestPlanDBModel) MarshalHelper.unmarshal(
TestPlanDBModel.class, httpResponse.getContent());
} catch (Exception e) {
handleException(httpResponse, e);
return null;
}
}
public TestPlanResponseModel deleteTestPlan(String accessToken,
String testPlanId) {
String url = this.getBaseUrl() + "/removeTestPlanFromPool";
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanId", testPlanId);
return getTestPlanResponseModel(url, params, accessToken);
}
public TestPlanResponseModel loadTestPlans(String accessToken) {
String url = this.getBaseUrl() + "/loadTestPlans";
return getTestPlanResponseModel(url, null, accessToken);
}
public HttpResponse getTestPlanReport(String accessToken,
String testPlanRunId) {
String url = this.getBaseUrl() + "/getTestPlanReport";
Map<String, String> params = new HashMap<String, String>();
params.put("testPlanRunID", testPlanRunId);
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendPost(url, params,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse))
return null;
return httpResponse;
} catch (IOException e) {
this.handleException(httpResponse, e);
return null;
}
}
private TestPlanResponseModel getTestPlanResponseModel(String url,
Map<String, String> params, String accessToken) {
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendPost(url, params,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return extractTestPlanResponseModel(httpResponse);
} catch (Exception e) {
this.handleException(httpResponse, e);
return createFailTestPlanResponseModel();
}
}
private TestPlanResponseModel createFailTestPlanResponseModel() {
TestPlanResponseModel testPlanResponseModel = new TestPlanResponseModel();
testPlanResponseModel.setSuccess(false);
testPlanResponseModel.setFailCause("");
return testPlanResponseModel;
}
private TestPlanResultModel getTestPlanResultModelByPost(String url,
Map<String, String> params, String accessToken) {
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendPost(url, params,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse))
return null;
return extractTestPlanResultModel(httpResponse);
} catch (Exception e) {
this.handleException(httpResponse, e);
return null;
}
}
private TestPlanResponseModel extractTestPlanResponseModel(
HttpResponse httpResponse) throws JAXBException,
UnsupportedEncodingException {
return (TestPlanResponseModel) MarshalHelper.unmarshal(
TestPlanResponseModel.class, httpResponse.getContent());
}
private TestPlanResultModel extractTestPlanResultModel(
HttpResponse httpResponse) throws JAXBException,
UnsupportedEncodingException {
return (TestPlanResultModel) MarshalHelper.unmarshal(
TestPlanResultModel.class, httpResponse.getContent());
}
public ScriptBriefResultModel getLatestScriptBriefResult(
String accessToken, String testPlanId, String scriptId) {
String url = this.baseUrl + "/scriptBrief" + "/" + testPlanId + "/"
+ scriptId + "/latestResult";
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return (ScriptBriefResultModel) MarshalHelper.tryUnmarshal(
ScriptBriefResultModel.class, httpResponse.getContent());
} catch (Exception e) {
handleException(httpResponse, e);
return null;
}
}
public ScriptPagesBriefModel getScriptPageBriefModel(String accessToken,
String testPlanId, String scriptId) {
String url = this.baseUrl + "/pagesBrief" + "/" + testPlanId + "/"
+ scriptId;
HttpResponse httpResponse = null;
try {
httpResponse = this.getHttpRequester().sendGet(url, null,
makeAccessTockenMap(accessToken));
if (!validateHttpResponse(httpResponse)) {
handleInvalidatedResponse(url);
return null;
}
return (ScriptPagesBriefModel) MarshalHelper.unmarshal(
ScriptPagesBriefModel.class, httpResponse.getContent());
} catch (Exception e) {
handleException(httpResponse, e);
return null;
}
}
public TestPlanResponseModel stopTestPlan(String accessToken,
String testPlanRunId) {
String url = this.baseUrl + "/stop" + "/" + testPlanRunId;
return getTestPlanResponseModel(url, null, accessToken);
}
}

View File

@ -1,176 +1,176 @@
package org.bench4q.web.test.masterMessager;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.*;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.TestPlanResponseModel;
import org.bench4q.share.models.master.TestPlanResultModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.web.masterMessager.TestPlanMessager;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/test/resources/bench4qweb-servlet.xml")
public class TestPlanMessageTest extends MessagerTestBase {
private TestPlanMessager testPlanMessager;
private String baseUrl = "/testPlan";
private String testPlanId = "testPlanId";
private String scriptId = "scriptId";
public TestPlanMessager getTestPlanMessager() {
return testPlanMessager;
}
@Autowired
public void setTestPlanMessager(TestPlanMessager testPlanMessager) {
this.testPlanMessager = testPlanMessager;
}
@BeforeClass
public static void setUp() {
startServer();
}
@AfterClass
public static void clear() {
stopServer();
}
@Test
public void test_runTestPlan() {
String url = baseUrl + "/run";
this.getWireMock().register(
post(urlEqualTo(url)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(this.createResponse())));
assertNotNull(this.testPlanMessager.runTestPlan(null, ""));
}
@Test
public void test_getRunningTestInfo() {
String url = baseUrl + "/getRunningInfo";
this.getWireMock().register(
post(urlEqualTo(url)).withRequestBody(containing("testPlanId"))
.willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(this.createResponse())));
assertNotNull(this.testPlanMessager.getRunningTestInfo(null, ""));
}
// @Test
// public void test_getScriptBriefResult() {
// TestPlanScriptBriefResultModel testPlanScriptBriefResultModel = new
// TestPlanScriptBriefResultModel();
// String response = MarshalHelper
// .tryMarshal(testPlanScriptBriefResultModel);
// String url = baseUrl + '/' + testPlanId + '/' + scriptId + '/'
// + duationBegin;
// System.out.println(url);
// this.getWireMock().register(
// get(urlEqualTo(url)).willReturn(
// aResponse().withStatus(200)
// .withHeader("Content-Type", "text/xml")
// .withBody(response)));
// assertNotNull(this.testPlanMessager.getScriptBriefResult(null,
// testPlanId, scriptId, duationBegin));
// }
@Test
public void test_getScriptBehaviorsBriefResult() {
ScriptBehaviorsBriefModel scriptBehaviorsBriefModel = new ScriptBehaviorsBriefModel();
scriptBehaviorsBriefModel.setFinished(true);
String response = MarshalHelper.tryMarshal(scriptBehaviorsBriefModel);
String url = baseUrl +"/getBehaviorsBrief"+ '/' + testPlanId + '/' + scriptId;
this.getWireMock().register(
get(urlEqualTo(url)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(response)));
assertNotNull(this.testPlanMessager.getScriptBehaviorsBriefResult(null,
testPlanId, scriptId));
assertTrue(this.testPlanMessager.getScriptBehaviorsBriefResult(null,
testPlanId, scriptId).isFinished());
}
// @Test
// public void test_getPageBriefResult() {
// ScriptPagesBriefModel scriptPagesBriefModel = new ScriptPagesBriefModel();
// String response = MarshalHelper.tryMarshal(scriptPagesBriefModel);
// String url = baseUrl + '/' + testPlanId + '/' + scriptId;
// this.getWireMock().register(
// get(urlEqualTo(url)).willReturn(
// aResponse().withStatus(200)
// .withHeader("Content-Type", "text/xml")
// .withBody(response)));
// assertNotNull(this.testPlanMessager.getPageBriefResult(null,
// testPlanId, scriptId));
// }
// @Test
// public void test_queryTestPlanById() {
// String testPlanRunId = "testPlanRunId";
// String url = baseUrl + "/queryTestPlan/" + testPlanRunId;
// this.getWireMock().register(
// get(urlEqualTo(url)).willReturn(
// aResponse().withStatus(200)
// .withHeader("Content-Type", "text/xml")
// .withBody(this.createResponse())));
// assertNotNull(this.testPlanMessager.queryTestPlanById(null,
// testPlanRunId));
// }
@Test
public void test_deleteTestPlan() {
TestPlanResponseModel testPlanResponseModel = new TestPlanResponseModel();
testPlanResponseModel.setSuccess(true);
String response = MarshalHelper.tryMarshal(testPlanResponseModel);
String url = baseUrl + "/removeTestPlanFromPool";
this.getWireMock().register(
post(urlEqualTo(url)).withRequestBody(containing("testPlanId"))
.willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(response)));
assertNotNull(this.testPlanMessager.deleteTestPlan(null, testPlanId));
assertTrue(this.testPlanMessager.deleteTestPlan(null, testPlanId)
.isSuccess());
}
@Test
public void test_loadTestPlans() {
String url = baseUrl + "/loadTestPlans";
TestPlanResponseModel testPlanResponseModel = new TestPlanResponseModel();
testPlanResponseModel.setSuccess(true);
String response = MarshalHelper.tryMarshal(testPlanResponseModel);
this.getWireMock().register(
post(urlEqualTo(url)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(response)));
assertNotNull(this.testPlanMessager.loadTestPlans(null));
assertTrue(this.testPlanMessager.loadTestPlans(null).isSuccess());
}
@Test
public void test_getTestPlanReport() {
}
public String createResponse() {
TestPlanResultModel testPlanResultModel = new TestPlanResultModel();
return MarshalHelper.tryMarshal(testPlanResultModel);
}
}
package org.bench4q.web.test.masterMessager;
import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.*;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.master.TestPlanResponseModel;
import org.bench4q.share.models.master.TestPlanResultModel;
import org.bench4q.share.models.master.statistics.ScriptBehaviorsBriefModel;
import org.bench4q.web.masterMessager.TestPlanMessager;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("file:src/test/resources/bench4qweb-servlet.xml")
public class TestPlanMessageTest extends MessagerTestBase {
private TestPlanMessager testPlanMessager;
private String baseUrl = "/testPlan";
private String testPlanId = "testPlanId";
private String scriptId = "scriptId";
public TestPlanMessager getTestPlanMessager() {
return testPlanMessager;
}
@Autowired
public void setTestPlanMessager(TestPlanMessager testPlanMessager) {
this.testPlanMessager = testPlanMessager;
}
@BeforeClass
public static void setUp() {
startServer();
}
@AfterClass
public static void clear() {
stopServer();
}
@Test
public void test_runTestPlan() {
String url = baseUrl + "/run";
this.getWireMock().register(
post(urlEqualTo(url)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(this.createResponse())));
assertNotNull(this.testPlanMessager.runTestPlan(null, ""));
}
@Test
public void test_getRunningTestInfo() {
String url = baseUrl + "/getRunningInfo";
this.getWireMock().register(
post(urlEqualTo(url)).withRequestBody(containing("testPlanId"))
.willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(this.createResponse())));
assertNotNull(this.testPlanMessager.getRunningTestInfo(null, ""));
}
// @Test
// public void test_getScriptBriefResult() {
// TestPlanScriptBriefResultModel testPlanScriptBriefResultModel = new
// TestPlanScriptBriefResultModel();
// String response = MarshalHelper
// .tryMarshal(testPlanScriptBriefResultModel);
// String url = baseUrl + '/' + testPlanId + '/' + scriptId + '/'
// + duationBegin;
// System.out.println(url);
// this.getWireMock().register(
// get(urlEqualTo(url)).willReturn(
// aResponse().withStatus(200)
// .withHeader("Content-Type", "text/xml")
// .withBody(response)));
// assertNotNull(this.testPlanMessager.getScriptBriefResult(null,
// testPlanId, scriptId, duationBegin));
// }
@Test
public void test_getScriptBehaviorsBriefResult() {
ScriptBehaviorsBriefModel scriptBehaviorsBriefModel = new ScriptBehaviorsBriefModel();
scriptBehaviorsBriefModel.setFinished(true);
String response = MarshalHelper.tryMarshal(scriptBehaviorsBriefModel);
String url = baseUrl +"/getBehaviorsBrief"+ '/' + testPlanId + '/' + scriptId;
this.getWireMock().register(
get(urlEqualTo(url)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(response)));
assertNotNull(this.testPlanMessager.getScriptBehaviorsBriefResult(null,
testPlanId, scriptId));
assertTrue(this.testPlanMessager.getScriptBehaviorsBriefResult(null,
testPlanId, scriptId).isFinished());
}
// @Test
// public void test_getPageBriefResult() {
// ScriptPagesBriefModel scriptPagesBriefModel = new ScriptPagesBriefModel();
// String response = MarshalHelper.tryMarshal(scriptPagesBriefModel);
// String url = baseUrl + '/' + testPlanId + '/' + scriptId;
// this.getWireMock().register(
// get(urlEqualTo(url)).willReturn(
// aResponse().withStatus(200)
// .withHeader("Content-Type", "text/xml")
// .withBody(response)));
// assertNotNull(this.testPlanMessager.getPageBriefResult(null,
// testPlanId, scriptId));
// }
// @Test
// public void test_queryTestPlanById() {
// String testPlanRunId = "testPlanRunId";
// String url = baseUrl + "/queryTestPlan/" + testPlanRunId;
// this.getWireMock().register(
// get(urlEqualTo(url)).willReturn(
// aResponse().withStatus(200)
// .withHeader("Content-Type", "text/xml")
// .withBody(this.createResponse())));
// assertNotNull(this.testPlanMessager.queryTestPlanById(null,
// testPlanRunId));
// }
@Test
public void test_deleteTestPlan() {
TestPlanResponseModel testPlanResponseModel = new TestPlanResponseModel();
testPlanResponseModel.setSuccess(true);
String response = MarshalHelper.tryMarshal(testPlanResponseModel);
String url = baseUrl + "/removeTestPlanFromPool";
this.getWireMock().register(
post(urlEqualTo(url)).withRequestBody(containing("testPlanId"))
.willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(response)));
assertNotNull(this.testPlanMessager.deleteTestPlan(null, testPlanId));
assertTrue(this.testPlanMessager.deleteTestPlan(null, testPlanId)
.isSuccess());
}
@Test
public void test_loadTestPlans() {
String url = baseUrl + "/loadTestPlans";
TestPlanResponseModel testPlanResponseModel = new TestPlanResponseModel();
testPlanResponseModel.setSuccess(true);
String response = MarshalHelper.tryMarshal(testPlanResponseModel);
this.getWireMock().register(
post(urlEqualTo(url)).willReturn(
aResponse().withStatus(200)
.withHeader("Content-Type", "text/xml")
.withBody(response)));
assertNotNull(this.testPlanMessager.loadTestPlans(null));
assertTrue(this.testPlanMessager.loadTestPlans(null).isSuccess());
}
@Test
public void test_getTestPlanReport() {
}
public String createResponse() {
TestPlanResultModel testPlanResultModel = new TestPlanResultModel();
return MarshalHelper.tryMarshal(testPlanResultModel);
}
}